Discuss / Python / 作业

作业

Topic source

import re

from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str):

    cday = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')#把用户输入的字符串转换成时间

    offset=int(re.match(r'^UTC([+|-]\d+):\d{2}$',tz_str).group(1))#通过字符串获取时区 

    # 把用户输入的时间转成标准时区时间,转换为timestamp  

    return cday.replace(tzinfo=timezone(timedelta(hours=offset))).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')


  • 1

Reply