Discuss / Python / 练习:使用两种方法,一种使用timezone,一种不使用timezone

练习:使用两种方法,一种使用timezone,一种不使用timezone

Topic source

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

方法一:

from datetime import datetime, timezone, timedelta

import re

# 使用timezone的方法

def to_timestamp(dt_str, tz_str):

    # 将时间字符串转换成datetime

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

    # 提取时区信息

    m = re.match(r'(\w+)(\+|\-)(\d+)', tz_str)

    if m.group(2) == '-':

        h = - int(m.group(3))

    else:

        h = int(m.group(3))

    # 创建本地时区

    tz_utc_x = timezone(timedelta(hours=h))

    # 拿到本地时区,并强制设置时区

    cur_dd = cur_dt.replace(tzinfo=tz_utc_x)

    # 创建北京时区

    tz_utc_8 = timezone(timedelta(hours=8))

    # 转化时区为北京时区

    bj_dt = cur_dd.astimezone(tz_utc_8)

    return bj_dt.timestamp()

方法二:

# 不使用timezone的方法

def to_timestamp(dt_str, tz_str):

    # 将时间字符串转成datetime

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

    # 提取时区hours,并计算UTC+8:00时区与该时区的时间差

    m = re.match(r'(\w+)(\+|\-)(\d+)', tz_str)

    if m.group(2) == '-':

        h1 = 8 + int(m.group(3))

    else:

        h1 = 8 - int(m.group(3))

    # 该地区时间加上时间差为北京时间

    dt2 = dt1 + timedelta(hours=h1)

    # 将北京时间转化为timestamp返回

    return dt2.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')

年少的你

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

请问为什么 group(1)是+7,而不是UTC


  • 1

Reply