from datetime import datetime #导入
now = datetime.now() #获取当前日期和时间,类型是datetime
dt = datetime(2015, 4, 19, 12, 20)
dt.timestamp() #datetime转换为timestamp
timestamp就是相对于epoch time的秒数,它的值与时区没有关系,而datetime与时区有关,计算机存储的当前时间是以timestamp表示的,任何计算机在任意时刻的timestamp都是完全相同的
datetime.fromtimestamp(t) #timestamp转换为datetime
datetime.utcfromtimestamp(t) #timestamp转换为UTC标准时区的datetime
datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') #str转datetime
now = datetime.now()
now.strftime('%a, %b %d %H:%M') #datetime转str
now = datetime.now()
now + timedelta(hours=10)
now - timedelta(days=1) #datetime加减操作
本地时间是指系统设定时区的时间,例如北京时间是UTC+8:00时区的时间,而UTC时间指UTC+0:00时区的时间。
>>> 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)))
我们可以先通过utcnow()
拿到当前的UTC时间,再转换为任意时区的时间
# 拿到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
假设你获取了用户输入的日期和时间如2015-1-21 9:01:30
,以及一个时区信息如UTC+5:00
,均是str
,请编写一个函数将其转换为timestamp
# 假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp
import re
from datetime import datetime, timezone, timedelta
def to_timestamp(dt_str, tz_str):
localTime = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
nowTimeZone = int(re.match(r'UTC([+-]\d+):\d+',tz_str).groups()[0])
tz_utc_now = timezone(timedelta(hours=nowTimeZone))
dt = localTime.replace(tzinfo=tz_utc_now)
return dt.timestamp()
t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
assert t1 == 1433121030.0, t1
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
assert t2 == 1433121030.0, t2
print('ok')