在Python中计算不同时区的时间

jin*_*ong 5 python datetime pytz

我正在使用来自两个不同时区的时间戳的数据集.以下是我要做的事情:

1.从字符串创建时间对象t1;

2.设置t1的时区;

3.在不同的时区推迟时间t2.

import time
s = "2014-05-22 17:16:15"
t1 = time.strptime(s, "%Y-%m-%d %H:%M:%S")
#Set timezone for t1 as US/Pacific
#Based on t1, calculate the time t2 in a different time zone
#(e.g, Central European Time(CET))
Run Code Online (Sandbox Code Playgroud)

任何答案/评论将不胜感激..!

Pad*_*ham 6

使用日期时间pytz

import datetime
import pytz
pac=pytz.timezone('US/Pacific')
cet=pytz.timezone('CET')
s = "2014-05-22 17:16:15"
t1 = datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
pacific = pac.localize(t1)
cet_eur = pacific.astimezone(cet)
print pacific
print cet_eur

2014-05-22 17:16:15-07:00
2014-05-23 02:16:15+02:00
Run Code Online (Sandbox Code Playgroud)

我想你想要datetime.timetuple

返回一个 time.struct_time,例如 time.localtime() 返回的值。时、分、秒均为 0,DST 标志为 -1。d.timetuple() 相当于 time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)),其中 yday = d.toordinal () - date(d.year, 1, 1).toordinal() + 1 是当年的天数,从 1 开始表示 1 月 1 日。

  print datetime.date.timetuple(t1)
  time.struct_time(tm_year=2014, tm_mon=5, tm_mday=22, tm_hour=17, tm_min=16, tm_sec=15, tm_wday=3, tm_yday=142, tm_isdst=-1)
Run Code Online (Sandbox Code Playgroud)

这是一个快速的草稿,但 pytz 文档有很多好的、清晰的例子