Discuss / Python / train

train

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):

    if re.match(r'UTC(\+|\-)(0?[0-9]):00', tz_str):

        r = re.match(r'UTC(\+|\-)(0?[0-9]):00', tz_str)

        if r.group(1) == '-':

            h = r.group(1)+r.group(2)[-1:]

        else:

            h = r.group(2)[-1:]

    else:

        raise ValueError

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

    tz = timezone(timedelta(hours=int(h)))

    dt = dt.replace(tzinfo=tz)

    return dt.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