官网时间格式说明:https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
导入模块:from datetime import datetime
查看系统当前时间
now = datetime.now() print (now)
运行结果:
2018-07-27 15:19:50
str转换为datetime
cday = datetime.strptime('2016-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') print (cday)
运行结果:
2016-06-01 18:19:59
datetime转换为str:给客户看
now = datetime.now() print(now.strftime('%a, %b %d %H:%M'))
运行结果:
Fri, Jul 27 03:56
datetime加减: 计算
from datetime import datetime, timedelta now = datetime.now() print (now) delta_add = now + timedelta(days = 3, hours=10, minutes = 1) print(delta_add) delta_add = now - timedelta(days = 1, hours=10, minutes = 1) print(delta_add)
运行结果:
2018-07-27 04:01:57.861809 2018-07-30 14:02:57.861809 2018-07-25 18:00:57.861809
本地时间转换为UTC时间:timezone
from datetime import datetime, timedelta, timezone tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00 print (tz_utc_8) now = datetime.now() print (now)
运行结果:
UTC+08:00 2018-07-29 03:27:01.248631
本地时间转换为UTC时间:replace
dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00 print (dt)
运行结果:
2018-07-29 03:27:01.248631+08:00
时区转换:astimezone
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) # 拿到UTC时间,并强制设置时区为UTC+0:00: print(utc_dt) bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) # astimezone()将转换时区为北京时间 print(bj_dt) tokyo_dt = bj_dt.astimezone(timezone(timedelta(hours=9))) # astimezone()将bj_dt转换时区为东京时间: print(tokyo_dt)
运行结果:
2018-07-29 03:42:40.795549+00:00 2018-07-29 11:42:40.795549+08:00 2018-07-29 12:42:40.795549+09:00
小结:
时区转换一定要用带有UTC时区的时间进行转换。
时区转换可以不从+00:00的基础时区转换,可以从其他带有UTC时区的时间转换,如:bj_dt-->tokyo_dt,但要确保前面时间的时区是正确的