Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 834
jinlong Avatar asked May 23 '14 00:05

jinlong


People also ask

How do you get different time zones in Python?

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.

How do you calculate time difference between time zones?

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.

How do I compare time differences in Python?

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.

How does Python handle time zones?

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.


1 Answers

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

like image 155
Padraic Cunningham Avatar answered Sep 30 '22 00:09

Padraic Cunningham