Discuss / Python / 还是交个作业

还是交个作业

Topic source

久疤_796

#1 Created at ... [Delete] [Delete and Lock User]
import re
from datetime import datetime,timezone,timedelta
def to_timestamp(dt_str,tz_str):
    def tzfun(tz_str):
        t = re.match(r'^UTC([-|+])([[0-9]|[0-1][1-9]|2[0-3]]+):([[0-5][0-9]|[0-9]]+)$',tz_str)
        delta = int(t.group(2))*3600+int(t.group(3))*60
        if t.group(1)=='-':
            delta = -delta
        return timezone(timedelta(0,delta))

    cday = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S').replace(tzinfo=tzfun(tz_str))
    return cday.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('pass')

  • 1

Reply