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')
    tz = re.match('^UTC([+-])(\d?\d):00$', tz_str)
    tz1 = tz.group(1)
    tz2 = int(tz.group(2))
    if tz1 == '+':
        tz_utc = timezone(timedelta(hours=tz2))
    else:
        tz_utc = timezone(timedelta(hours=-tz2))
    dt = dt.replace(tzinfo=tz_utc)
    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')

#输出
ok


  • 1

Reply