Discuss / Python / Homework of Datetime

Homework of Datetime

Topic source

郝仁E哥

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

作业:

# -*- coding:utf-8 -*-

import re
from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str,tz_str):
#str转换为datetime
dt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') 
#从正则表达式中提取出时区差值
tz_hours=int(re.match(r'UTC[+-]{1}(\d+):\d{2}',tz_str).group(1))
## 创建时区UTC+tz_hours
tz_utc=timezone(timedelta(hours=tz_hours))
# 强制设置为UTC+tz_utc
dt=dt.replace(tzinfo=tz_utc)
return dt.timestamp()  #返回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')

郝仁E哥

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

上面的排版没排好!不能删除,在这里更正

# -*- coding:utf-8 -*-

import re
from datetime import datetime, timezone, timedelta

def to_timestamp(dt_str,tz_str):
       #str转换为datetime
    dt=datetime.strptime(dt_str,'%Y-%m-%d %H:%M:%S') 
       #从正则表达式中提取出时区差值
    tz_hours=int(re.match(r'UTC[+-]{1}(\d+):\d{2}',tz_str).group(1))
       # 创建时区UTC+tz_hours
    tz_utc=timezone(timedelta(hours=tz_hours))
       # 强制设置为UTC+tz_utc
    dt=dt.replace(tzinfo=tz_utc)
    return dt.timestamp()  #返回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')

稍稍更正一下,group提取时区差是应该加上符号: tz_hours = int(re.match(r'UTC([+-]\d+):00',tz_str).group(1))#提取出时区差


  • 1

Reply