Discuss / Python / 交作业

交作业

Topic source

#1 Created at ... [Delete] [Delete and Lock User]

import re

from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str='UTC+00:00'):

    dt = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')

    tz_int = 0

    try:

        m = re.match(r'^UTC(.\d{1,2}):00',tz_str)

        if m.group(1):

            tz_int = int(m.group(1))

    except Exception as e:

        print(e,'\nPlease check you format of timezone, it have to like this \'UTC+07:00\'')

    tz_utc = timezone(timedelta(hours=tz_int))

    result = dt.replace(tzinfo=tz_utc)

    return result.timestamp()

# 测试:

t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+07: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