Convert a UTC time to epoch
date, datetime, python
Solution
The solution was to use the calendar module (inspired from here)
>>>#Quick and dirty demo
>>>print calendar.timegm(datetime.datetime.utcnow().utctimetuple()) - time.time()
>>>-0.6182510852813721
And here is the conversion function:
import calendar, datetime, time
#Timestamp is a datetime object in UTC time
def UTC_time_to_epoch(timestamp):
epoch = calendar.timegm(timestamp.utctimetuple())
return epoch
Problem
I am looking to analyze traffic flow with relation to weather data. The traffic data has a UNIX timestamp (aka epoch), but I am running into trouble with converting the timestamp (in the weather data) to epoch. The problem is that I am in Norway and the UTC timestamp in the weather data isn't in the same timezone as me (GMT+1). My initial approach I first tried converting it into epoch and treating the data as if it was in the GMT+1 timezone. Then I compensated by subtracting the difference in number of seconds between UTC and GMT+1. Problems with the approach I realize first of all that this approach is very primitive and not very elegant (in fact probably it is at best an ugly hack). However, the biggest problem here is that the difference between UTC and GMT+1 is not constant (due to daylight savings). Question Is there any reliable way of turning UTC time to a UNIX time stamp in python (taking into account that my machine is in GMT+1)? The timestamp is in the following format: `Y-m-d HH:MM:SS` Edit: Tried rmunns' solution: ``` def convert_UTC_to_epoch(timestamp): tz_UTC = pytz.timezone('UTC') time_format = "%Y-%m-%d %H:%M:%S" naive_timestamp = datetime.datetime.strptime(timestamp, time_format) aware_timestamp = tz_UTC.localize(naive_timestamp) epoch = aware_timestamp.strftime("%s") return (int) (epoch) ``` This does not work properly as evidenced below: ``` #Current time at time of the edit is 15:55:00 UTC on June 9th 2014. >>> diff = time.time() - convert_UTC_to_epoch("2014-06-09 15:55:00") >>> diff 3663.25887799263 >>> #This is about an hour off. ```