Discuss / Python / 交作业

交作业

Topic source
import re
from datetime import datetime, timezone, timedelta
def to_timestamp(dt_str, tz_str):
    #抓取并创建
    tz = re.match(r'(UTC)([\+|\-]\d+):(\d+)',tz_str)
    tz = tz.group(2)
    tz_utc = timezone(timedelta(hours = int(tz)))
    #将str转化为datetime
    dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
    #强制设置时区
    dt = dt.replace(tzinfo=tz_utc) 
    #转化为timestamp
    t = dt.timestamp()
    return t


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')



  • 1

Reply