datetime
datetime是Python处理日期和时间的标准库
版本:python3.6
datetime.datetime
获取当前日期和时间
>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2018, 11, 1, 20, 49, 35, 93299)
>>> print(now)
2018-11-01 20:49:35.093299
>>> print(type(now))
<class 'datetime.datetime'>
获取当前时间年月日
>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now)
2018-11-01 21:08:40.781382
>>> print(now.year)
2018
>>> print(now.month)
11
>>> print(now.day)
1
获取指定日期和时间
要指定某个日期和时间,我们直接用参数构造一个datetime
:
>>> from datetime import datetime
>>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
>>> print(dt)
2015-04-19 12:20:00
datetime转换为timestamp
>>> from datetime import datetime
>>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime
>>> dt.timestamp() # 把datetime转换为timestamp
1429417200.0
timestamp转换为datetime
>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00
str转换为datetime
>>> from datetime import datetime
>>> cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
>>> print(cday)
2015-06-01 18:19:59
datetime转换为str
>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2018, 11, 1, 21, 21, 44, 436934)
>>> print(now)
2018-11-01 21:21:44.436934
>>> now.strftime('%Y-%m-%d %H:%M:%S')
'2018-11-01 21:21:44'
datetime加减
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
本地时间转换为UTC时间
>>> from datetime import datetime, timedelta, timezone
>>> tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012)
>>> dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00
>>> dt
datetime.datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=datetime.timezone(datetime.timedelta(0, 28800)))
时区转换
# 拿到UTC时间,并强制设置时区为UTC+0:00:
>>> utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
>>> print(utc_dt)
2015-05-18 09:05:12.377316+00:00
# astimezone()将转换时区为北京时间:
>>> bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
>>> print(bj_dt)
2015-05-18 17:05:12.377316+08:00
# astimezone()将转换时区为东京时间:
>>> tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
>>> print(tokyo_dt)
2015-05-18 18:05:12.377316+09:00
# astimezone()将bj_dt转换时区为东京时间:
>>> tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
>>> print(tokyo_dt2)
2015-05-18 18:05:12.377316+09:00
datetime.date
获取当前日期及年月日
>>> import datetime
>>> now_date = datetime.date.today()
>>> print(now_date)
2018-11-01
>>> print(now_date.year)
2018
>>> print(now_date.month)
11
>>> print(now_date.day)
1