Search code examples
pythondatetimepytz

Calculate time in a different timezone in Python


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..!


Solution

  • 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