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

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

Topic source

Normaloo

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding:utf-8 -*-

import re
from datetime import datetime, timezone, timedelta

# 测试:
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')

Normaloo

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

def to_timestamp(dt_str, tz_str):

    s =re.match(r'^UTC(.)(\d+):00$',tz_str).group(1)#获取符号—或+

    d0=re.match(r'^UTC(.)(\d+):00$',tz_str).group(2)#获取时区

    d=int(d0)

    cday=datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') #str转换为datetime

    t0=cday.timestamp() #按照+8时区转换为timestamp

    if s=='-':   #依照原时区补上相差时间

        t=t0+(8+d)*3600

    elif s=='+':

        t=t0+(8-d)*3600

    return t


  • 1

Reply