Discuss / Python / 正则去出来后报错了,没太明白需要这么转换

正则去出来后报错了,没太明白需要这么转换

Topic source

-- coding: utf-8 --

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

import re from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str, tz_str): m = re.match(r'^UTC([+|-])(0?[0-9]|1[0-1]):\d*', tz_str) # 正则匹配 pos = m.group(1) # 提取第一个()的正负号 num = m.group(2) # 提取第二个括号的时间 if pos == '-': # 如果是负号 num = -num dt_date = (dt_str, '%Y-%m-%d %H:%M:%S') # str转换成datetime utc_dt_date = dt_date + timedelta(hours=num) # 加上或减去的时区的时间 return utc_dt_date.timestamp() # datetime 转换成timestamp

t1 = to_timestamp('2016-02-05 17:52:30', 'UTC+8:00') print(t1)

t2 = to_timestamp('2016-02-05 17:52:30', 'UTC-11:00') print(t2)**

看很多人正则取出来的都没有转换成int型,这个代码报错了,如下(求解答下): Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled/PythonExcise/Functions/DatetimeExcise.py", line 16, in <module> t1 = to_timestamp('2016-02-05 17:52:30', 'UTC+8:00') File "C:/Users/Administrator/PycharmProjects/untitled/PythonExcise/Functions/DatetimeExcise.py", line 13, in to_timestamp utc_dt_date = dt_date + timedelta(hours=num) # 加上或减去的时区的时间 TypeError: unsupported type for timedelta hours component: <strong>str</strong>


  • 1

Reply