klenwell information services : PythonDateTime

Python Dates and Times

return to DevPython

String to Date

from datetime import datetime, timedelta

>>> christmas = datetime.strptime('2010-12-25', '%Y-%m-%d')
>>> christmas
datetime.datetime(2010, 12, 25, 0, 0)
>>> christmas - timedelta(days=1)
datetime.datetime(2010, 12, 24, 0, 0)
>>> christmas.date()
datetime.date(2010, 12, 25)
>>> str(christmas.date())
'2010-12-25'
>>> datetime.strptime('2010-12-25', '%Y-%m-%d').date()
datetime.date(2010, 12, 25)


Date to String (Date Formatting)

>>> from datetime import date, datetime
>>> datetime.now().strftime("%Y%m%d%H%M%S")
'20111014140517'
>>> 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)


Datetime to Date / Date to Datetime

>>> from datetime import date, datetime, time
>>> today = date.today()
>>> today_as_datetime = datetime.combine(today, time())
>>> today_as_datetime
datetime.datetime(2012, 6, 4, 0, 0)

>>> now = datetime.now()
>>> now_as_date = now.date()
>>> now_as_date
datetime.date(2012, 6, 4)


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