python 获取年月日时分秒
时间: 2023-09-14 10:11:48 浏览: 137
你可以使用 Python 中的 datetime 模块来获取当前日期和时间。下面是一个示例代码:
```python
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(year, month, day, hour, minute, second)
```
输出将是当前日期和时间的年、月、日、时、分、秒。
相关问题
python获取年月日时分秒
以下是两种Python获取当前时间的年月日时分秒的例子:
1. 使用time模块获取当前时间并格式化输出年月日时分秒:
```python
import time
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
print(now_time) # 输出:2022-08-09 16:43:35
```
2. 使用datetime模块获取当前时间的年月日时分秒:
```python
import datetime
today = datetime.datetime.today()
currentYear = today.year
currentMonth = today.month
currentDay = today.day
currentHour = today.hour
currentMinute = today.minute
currentSecond = today.second
print(currentYear, currentMonth, currentDay, currentHour, currentMinute, currentSecond) # 输出:2022 8 9 16 45 22
```
python 获取年月日时分秒时间戳
你可以使用 Python 中的 `time` 模块来获取当前时间的时间戳。以下是获取年月日时分秒时间戳的示例代码:
```python
import time
# 获取当前时间戳
timestamp = time.time()
# 将时间戳转换为结构化时间
struct_time = time.localtime(timestamp)
# 获取年月日时分秒
year = struct_time.tm_year
month = struct_time.tm_mon
day = struct_time.tm_mday
hour = struct_time.tm_hour
minute = struct_time.tm_min
second = struct_time.tm_sec
# 打印结果
print("年份:", year)
print("月份:", month)
print("日期:", day)
print("小时:", hour)
print("分钟:", minute)
print("秒数:", second)
# 获取当前时间的时间戳
current_time = int(time.time())
print("当前时间戳:", current_time)
```
执行以上代码,输出结果如下:
```
年份: 2021
月份: 10
日期: 15
小时: 23
分钟: 55
秒数: 43
当前时间戳: 1634331343
```
阅读全文