Python datetime

From wikinotes

Basics

datetime

import datetime

now = datetime.datetime.now()    # datetime.datetime is a combination of date & time
now.strftime("%H:%M")
#> 08:22

now = datetime.date.today()      # datetime.date is only the YEAR/MONTH/DAY aspect of datetime
now.strftime("%m-%d-%y")         # get info from 'now' object
#> 09-22-2014

datetime_obj = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

datetime arithmetic

import datetime

yearA = datetime.timedelta( hour=1 )
yearB = datetime.timedelta( hour=2 )
diff  = yearB - yearA
diff.total_seconds()
#> 3600       ## One hour's difference in seconds

timezones

Timezones are not implemented in the python2 standard library. You can work around it by manually calculating your UTC offset.

NOTE:

You can do this yourself, but I highly recommend using python pytz instead.


WARNING:

You should always immediately sanitize all date inputs as UTC. Localize datetimes only for user fields, reports, etc.

dt        = datetime.datetime.now()
tz_offset = datetime.timedelta(seconds=time.altzone)

utc_dt = (dt + tz_offset)

Best Practices

UTC

Always store dates as UTC.

See python pytz for help.

ISO 8601

ISO 8601 is the officially recognized format for recording datetime objects in text.

to iso8601

dt = datetime.datetime.now( tzinfo=pytz.utc )
dt.isoformat()
>>> '2017-01-18T20:42:02.927528+00:00'

from iso8601

import dateutil.parser

dateutil.parser.parse('2017-01-18T20:42:02.927528+00:00')