Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find difference between times in different timezones in Python?

I am trying to calculate difference(in seconds) between two date/times formatted as following:

2010-05-11 17:07:33 UTC

2010-05-11 17:07:33 EDT

time1 = '2010-05-11 17:07:33 UTC'
time2 = '2010-05-11 17:07:33 EDT'
delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\
        time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z"))

The problem I got is EDT is not recognized, the specific error is

ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'
like image 644
JasonA Avatar asked May 13 '10 15:05

JasonA


2 Answers

Check out the pytz world timezone definitions library.

This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).

It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).

like image 190
Dolph Avatar answered Nov 14 '22 12:11

Dolph


In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding.

Here's a sample of using them together:

from datetime import datetime

from dateutil.relativedelta import *
import pytz

if __name__ == '__main__':
    date_one = datetime.now(pytz.timezone('US/Eastern'))
    date_two = datetime.now(pytz.timezone('US/Mountain'))
    rdelta = relativedelta(date_one, date_two)
    print(rdelta)
like image 44
Hank Gay Avatar answered Nov 14 '22 11:11

Hank Gay