How do I use timezones with a datetime object in python?

Posted by jidar on Stack Overflow See other posts from Stack Overflow or by jidar
Published on 2008-09-22T20:44:39Z Indexed on 2010/06/08 10:32 UTC
Read the original article Hit count: 254

Filed under:
|
|

How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone()

import datetime, re
from datetime import tzinfo

class myTimeZone(tzinfo):
    """docstring for myTimeZone"""
    def utfoffset(self, dt):
    	return timedelta(hours=1)

def myDateHandler(aDateString):
    """u'Sat,  6 Sep 2008 21:16:33 EDT'"""
    _my_date_pattern = re.compile(r'\w+\,\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d+)\:(\d+)\:(\d+)')
    day, month, year, hour, minute, second = _my_date_pattern.search(aDateString).groups()
    month = [
    		'JAN', 'FEB', 'MAR', 
    		'APR', 'MAY', 'JUN', 
    		'JUL', 'AUG', 'SEP', 
    		'OCT', 'NOV', 'DEC'
    ].index(month.upper()) + 1
    dt = datetime.datetime(
    	int(year), int(month), int(day), 
    	int(hour), int(minute), int(second)
    )					
    # dt = dt - datetime.timedelta(hours=1)
    # dt = dt - dt.tzinfo.utfoffset(myTimeZone())
    return (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, 0, 0, 0)

def main():
    print myDateHandler("Sat,  6 Sep 2008 21:16:33 EDT")

if __name__ == '__main__':
    main()

© Stack Overflow or respective owner

Related posts about python

Related posts about datetime