Discuss / Python / 交作业

交作业

Topic source

datetime 模块

获取用户输入的日期和时间如2015-1-21 9:01:30,以及一个时区信息

如UTC+5:00,均是str,请编写一个函数将其转换为timestamp

-- coding:utf-8 --

import re from datetime import datetime,timezone,timedelta

re_datetime = re.compile(r'^(\d{4})-(0[1-9]|1[0-2]|[1-9])-(0[1-9]|1[0-2]|2[0-9]|3[0-1]|[0-9])' r'\s(0[0-9]|1[0-9]|2[0-3]|[0-9])' r':(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])' r':(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$') re_timezone = re.compile(r'^(UTC)(+|-)([0-9]|0[0-9]|1[0-2]):(00)$')

def to_timestamp(dt_str,tz_str): m = re_datetime.match(dt_str) n = re_timezone.match(tz_str) if m and n: cdatetime = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') if(n[1] == '+'): cdatetime = cdatetime + timedelta(hours = int(n[3])) else: cdatetime = cdatetime - timedelta(hours = int(n[3])) return cdatetime.timestamp() elif n and not m: print('datetime is wrong') elif not n and m: print('timezone is wrong') else: print('both timezone and datetime are wrong')

t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') assert t1 == 1433121030.0

t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00') assert t2 == 1433121030.0

print('ok')


  • 1

Reply