Reputation: 15136
I have a program that recieves a date-time string in local time (israel) and i need to convert it to epoch seconds.
I could use a format such as "UTC +02:00" i guess, but the problem is, with daytime savings, Israels watch behaves differently than other countries. Is there a way to get epoch time dependant on country?
Upvotes: 0
Views: 6894
Reputation: 2041
To know whether to adjust for daylight savings, use:
time.daylight
This seems to work for me:
>>> time.gmtime(time.mktime(time.strptime("7 Nov 2011 12:12:12", "%d %b %Y %H:%M:%S")))
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=7, tm_hour=19, tm_min=12, tm_sec=12, tm_wday=0, tm_yday=311, tm_isdst=0)
Upvotes: 0
Reputation: 212835
> import pytz
> pytz.country_timezones['il'] # Israel
['Asia/Jerusalem']
Does this describe your timezone?
If yes, then you can use:
from datetime import datetime
import pytz
a = "2011-11-07 12:34:56"
dt = pytz.timezone('Asia/Jerusalem').localize(datetime.strptime(a, '%Y-%m-%d %H:%M:%S')).astimezone(pytz.utc)
dt
is now datetime.datetime(2011, 11, 7, 10, 34, 56, tzinfo=<UTC>)
, which is "2011-11-07 12:34:56" (in Jerusalem).
In order to convert it to epoch seconds (Unix timestamp, i.e. seconds since 1970-01-01 00:00:00 UTC), you can directly use:
import calendar
from datetime import datetime
import pytz
a = "2011-11-07 12:34:56"
epoch = calendar.timegm(pytz.timezone('Asia/Jerusalem').localize(datetime.strptime(a, '%Y-%m-%d %H:%M:%S')).utctimetuple())
# epoch is 1320662096
Upvotes: 6
Reputation: 19347
Yes, there is. The pytz
module incorporates the Olson database of political time zones and allows you to construct a local time object and convert between time zones. You look up the time zones by name. UTC is Etc/UTC
.
Upvotes: 0
Reputation: 308121
Python doesn't include any built-in timezone classes other than the base class tzinfo, which is useless. You need to install another package such as pytz.
Note that you'll have problems with ambiguous local times when the daylight savings changes, when the same time happens twice. It's always best if you can store and transfer the time in UTC and only convert when displaying. I realize that's not always possible.
Upvotes: 0