5

I'm working with a dataset with timestamps from two different time zones. Below is what I am trying to do:

1.Create a time object t1 from a string;

2.Set the timezone for t1;

3.Infer the time t2 at a different timezone.

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))

Any answers/comments will be appreciated..!

jinlong
  • 839
  • 1
  • 9
  • 19

1 Answers1

6

Use datetime and 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

I think you want datetime.timetuple

Return a time.struct_time such as returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple() is equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)), where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.

  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)

That is a quick draft but the pytz docs have lots of good and clear examples

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thanks, Padraic! That works perfect. Is there a quick way to convert datetime.datetime object into a time.struct_time object? I saw a lot of examples to do another way around. – jinlong May 23 '14 at 01:11
  • Hi Padraic, thanks again! The datetime.date.timetuple() works, except it discard the time info (i.e., H:M:S) so I suggest to change the answer to datetime.datetime.timetuple(). – jinlong May 23 '14 at 17:02
  • @jinlong, sorry, yes of course it should have been datetime.timetuple, I have updated the answer. – Padraic Cunningham May 23 '14 at 17:08