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..!
Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.
A simple calculation is required to get the number of degrees in each zone. 360 degrees can be divided by 24 hours in a day to arrive at the answer of 15. In other words, each time zone is comprised of 15 degrees of longitude and differs from each other by an hour.
To get a time difference in seconds, use the timedelta. total_seconds() methods. Multiply the total seconds by 1000 to get the time difference in milliseconds. Divide the seconds by 60 to get the difference in minutes.
So in order to work with the timezone smoothly, it is recommended to use the UTC as your base timezone. To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the 'pytz. utc' as a parameter to now() function as 'now(pytz.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With