python 中的时间与时区

带时区与不带时区不能直接加减运算,我们可以把时间统一到带UTC+00:00时区下时间进行运算。

  • 时间与时区
from datetime import datetime, timezone, timedelta
# 创建时区UTC+00:00
tz_utc = timezone(timedelta(hours=0))
# 获得带时区的UTC时间
current_time_utc = datetime.utcnow().replace(tzinfo=tz_utc)
print("current_time_utc:", current_time_utc)

# 创建时区UTC+08:00
tz_utc = timezone(timedelta(hours=8))
# 获得带时区的UTC+08:00时间
current_time_utc_8 = datetime.utcnow().replace(tzinfo=tz_utc)
print("current_time_utc_8:", current_time_utc_8)

# 本地时间
current_time = datetime.now()
print("current_time", current_time)

# 本地时区
local_time_zone = (datetime.now() - datetime.utcnow()).seconds / 3600
print("local_time_zone", local_time_zone)
  • 运行结果
current_time_utc: 2019-03-07 07:24:15.091095+00:00
current_time_utc_8: 2019-03-07 07:24:15.093092+08:00
current_time 2019-03-07 15:24:15.093092
local_time_zone 8.0
[Finished in 0.6s]
  • class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
>>> import datetime
>>> datetime.timedelta(days=1,hours=1,minutes=60, seconds=30,microseconds=25)
datetime.timedelta(1, 7230, 25)
>>> datetime.timedelta(days=1,hours=24,minutes=60, seconds=30,microseconds=25)
datetime.timedelta(2, 3630, 25)
>>> datetime.timedelta(hours=1)
datetime.timedelta(0, 3600)
>>> datetime.timedelta(hours=25)
datetime.timedelta(1, 3600)
>>> datetime.timedelta(seconds=30)
datetime.timedelta(0, 30)

你可能感兴趣的:(python3)