python怎么拿到当前时间的各年月日
时间: 2023-05-24 21:05:40 浏览: 73
你可以使用Python的datetime模块来获取当前时间的年月日。下面是一个示例代码:
```python
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
print("当前时间是:{}年{}月{}日".format(year, month, day))
```
输出结果为:当前时间是:2021年10月8日
相关问题
python获取当前时间,年月日时分秒
Python获取当前时间,年月日时分秒有两种方法,分别是:
1. 第一种方法,代码如下:(获取当前时间,提取当前日期/时间数字)
```
import time
nowtime1 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
t1 = ''.join([x for x in nowtime1 if x.isdigit()])
print(nowtime1) #获取当前时间(年-月-日 时:分:秒)
print(t1) #把当前时间提取数字部分(非时间戳),进而方便计算时间差
```
第一种方法的运行结果(精度较低):
```
2022-08-23 16:22:34
20220823162234
```
2. 第二种方法,代码如下:(获取当前时间,提取日期/时间数字,获取时间差【时:分:秒】)
```
import datetime,time
starttime = datetime.datetime.now()
'''代码程序模块浪费时间放在该段上下面'''
########################################
'''## 此处代表多行代码'''
########################################
'''代码程序模块浪费时间放在该段上下面'''
endtime = datetime.datetime.now()
t2_1 = str(endtime - starttime)
lst = t2_1.split('.')[0].split(':')
lst.append(t2_1.split('.')[1])
h,m,s,ms = lst[0],lst[1],lst[2],lst[3]
print('\n时间差--》 {}时{}分{}秒(+0.{}秒)'.format(h,m,s,ms) )
```
第二种方法的运行结果(精度较高):
```
2022-08-23 16:22:34.123456
2022-08-23 16:22:40.123456
时间差--》 0时0分6秒(+0.123456秒)
```
Python获取当前系统时间 年月日时分秒
你可以使用 Python 中的 `datetime` 模块来获取当前系统时间的年月日时分秒。下面是一个示例代码:
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 输出当前时间的年月日时分秒
print("当前时间为:{}".format(now.strftime("%Y-%m-%d %H:%M:%S")))
```
输出结果类似于:
```
当前时间为:2022-03-06 10:01:23
```