Discuss / Python / 练习题答案

练习题答案

Topic source

希望对你们有帮助

import re
from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str):
    dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') # str-->datetime
    tz_r = re.match(r'^UTC([+|-]\d{1,2}):00$', tz_str) #UTC中获取时区信息
    tz = timezone(timedelta(hours=int(tz_r.group(1)))) # 创建时区UTC
    dt = dt.replace(tzinfo=tz) # 利用tzinfo属性将datetime设置成指定时区
    return dt.timestamp() # 返回timestamp

t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
print(t1)
print(t2)

  • 1

Reply