熟悉datetime模块

假设你获取了用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息如UTC+5:00,均是str,请编写一个函数将其转换为timestamp:

#!/usr/bin/env python
# ! -*- coding: UTF-8 -*-
__time__ = '2017/12/12 0012 下午 6:09'
__author__ = 'Zhangge'

import re
from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str):
    tz_str = int(re.findall(r'^UTC([+-]+[0-9]+)\:0{2}', tz_str)[0])
    dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')  # str转换为datetime
    dt_timestamp = (dt + timedelta(hours=-tz_str+8)).timestamp() # 减去时区获取utc0:00时间加上8:00
    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')

你可能感兴趣的:(熟悉datetime模块)