Python Dates and Times

return to DevPython

String to Date

from datetime import datetime, timedelta

christmas = datetime.strptime('2010-12-25 00:00:00', '%Y-%m-%d %H:%M:%S')
christmas_eve = christmas - timedelta(days=1)
christmas_date = christmas.date()
christmas_date_str = str(christmas)



Date to String (Date Formatting)

>>> from datetime import date, datetime
>>> datetime.now().strftime('It is %H:%M:%S on %d %h %Y')
'It is 14:05:17 on 14 Oct 2011'
>>> date.today().strftime('Today is %Y-%m-%d')
'Today is 2011-10-14'


Time Delta

reference: http://docs.python.org/library/datetime.html#timedelta-objects
from datetime import date, datetime, timedelta

now = datetime.now() - timedelta(days=1)
a_day_ago = now - timedelta(days=1)
a_day_from_now = now + timedelta(days=1)

today = date.today()
yesterday = today - timedelta(days=1)
tomorrow = today + timedelta(days=1)


RFC 3339

reference: http://stackoverflow.com/questions/8556398/generate-rfc-3339-timestamp-in-python

With decimal seconds stripped:
>>> from datetime import datetime
>>> datetime.utcnow().isoformat("T").rsplit('.')[0] + "Z"
'2012-01-12T19:36:34Z'


Time Zones

reference: http://docs.python.org/library/datetime.html#tzinfo-objects

For a Google App Engine project I'm working on, I have to sync the app's time zone, which on the App Engine servers is UTC, to a Google Analytic profile's (i.e. site's) time zone, which defaults to US/Pacific.

Sample Code:
from datetime import datetime, timedelta

GA_OFFSET=-8     # PST (offset from UTC -- ignoring DST)

def sync_now():
   return datetime.utcnow() + timedelta(hours=GA_OFFSET)

def sync_today():
   return sync_now().date()


References

http://docs.python.org/library/datetime.html
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
Valid XHTML 1.0 TransitionalValid CSSWikkaWiki