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):
    cday = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
    zone = re.match(r'UTC([+-]\d{1,2}):(\d+)', tz_str)
    tz_hours = int(zone.group(1))
    tz_minutes = int(zone.group(2))

    # 计算时区偏移    
    tz_offset = timezone(timedelta(hours=tz_hours, minutes=tz_minutes))

    # 使用时区信息将日期时间转换为时间戳    
    dt = cday.replace(tzinfo=tz_offset)
    timestamp = dt.timestamp()
    return 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