Discuss / Python / 作业

作业

Topic source

Eliefly

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import re
from datetime import datetime, timedelta, timezone

def to_timestamp(dt_str,tz_str):
    m = re.match('UTC([+|-])(0?[0-9]|1[0-2]):\d*',tz_str)        #正则表达匹配
    pos = m.group(1)     #匹配的字符串分组提取
    num = int(m.group(2))   #匹配的字符串分组提取
    if pos == '-':  #负(西)时区
        num = -num
    utc_zone = timezone(timedelta(hours=num))   #创建时区
    dt = datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S')  #str转换为datetime
    dt = dt.replace(tzinfo=utc_zone)    #本地时间转换为UTC时间,强制设置为创建的时区
    return dt.timestamp()   #datetime转换为timestamp

t1 = to_timestamp('2015-6-1 08:10:30','UTC+7:00')
print('时间1:')
print(t1)
t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
print('时间2:')
print(t2)

# 运行结果:
# 时间1:
# 1433121030.0
# 时间2:
# 1433121030.0

  • 1

Reply