py 9
py 9
to hero in Python 3
✔ Create games with Python, like Tic Tac Toe and Blackjack!
✔ Learn advanced Python features, like the collections module and how to work with timestamps!
✔ Understand how to use both the Jupyter Notebook and create .py files
Watch Today →
object
Python 3.2+ has support for %z format when parsing a string into a datetime object.
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
import datetime
dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")
For other versions of Python, you can use an external library such as dateutil, which makes parsing a
string with
import dateutil.parser
dt = dateutil.parser.parse("2016-04-15T08:27:18-0500")
By default all datetime objects are naive. To make them timezone-aware, you must attach a tzinfo
object, which
provides the UTC offset and timezone abbreviation as a function of date and time.
For time zones that are a fixed offset from UTC, in Python 3.2+, the datetime module provides the
timezone class, a
concrete implementation of tzinfo, which takes a timedelta and an (optional) name parameter:
JST = timezone(timedelta(hours=+9))
print(dt)
# 2015-01-01 12:00:00+09:00
print(dt.tzname())
# UTC+09:00
print(dt.tzname)
# 'JST'
For Python versions before 3.2, it is necessary to use a third party library, such as dateutil. dateutil
provides an
equivalent class, tzoffset, which (as of version 2.5.3) takes arguments of the form
dateutil.tz.tzoffset(tzname,
print(dt)
# 2015-01-01 12:00:00+09:00
print(dt.tzname)
# 'JST'
For zones with daylight savings time, python standard libraries do not provide a standard class, so it
is necessary to
use a third party library. pytz and dateutil are popular libraries providing time zone classes.
In addition to static time zones, dateutil provides time zone classes that use daylight savings time
(see the
documentation for the tz module). You can use the tz.gettz() method to get a time zone object, which
can then
print(dt_l)
# 2015-01-01 12:00:00-05:00
print(dt_pst)
# 2015-01-01 12:00:00-08:00
print(dt_pdt)
# 2015-07-01 12:00:00-07:00
CAUTION: As of version 2.5.3, dateutil does not handle ambiguous datetimes correctly, and will
always default to
the later date. There is no way to construct an object with a dateutil timezone representing, for
example
2015-11-01 1:30 EDT-4, since this is during a daylight savings time transition.
All edge cases are handled properly when using pytz, but pytz time zones should not be directly
attached to time
zones through the constructor. Instead, a pytz time zone should be attached using the time zone's
localize
method:
import pytz
PT = pytz.timezone('US/Pacific')
print(dt_pst)
# 2015-01-01 12:00:00-08:00
print(dt_pdt)
# 2015-11-01 00:30:00-07:00
Be aware that if you perform datetime arithmetic on a pytz-aware time zone, you must either
perform the
calculations in UTC (if you want absolute elapsed time), or you must call normalize() on the result:
print(dt_new)
# 2015-11-01 03:30:00-07:00
dt_corrected = PT.normalize(dt_new)
print(dt_corrected)
# 2015-11-01 02:30:00-08:00
now = datetime.now()
delta = now-then
print(delta.days)
# 60
print(delta.seconds)
# 40826
return date_n_days_after.strftime(date_format)
return date_n_days_ago.strftime(date_format)
The datetime module contains three primary types of objects - date, time, and datetime.
import datetime
# Date object
today = datetime.date.today()
# Time object
# Current datetime
now = datetime.datetime.now()
# Datetime object
Arithmetic operations for these objects are only supported within same datatype and performing
simple arithmetic
noon-today
# Do this instead
# Or this
To switch between time zones, you need datetime objects that are timezone-aware.
utc = tz.tzutc()
local = tz.tzlocal()
utc_now = datetime.utcnow()
utc_now = utc_now.replace(tzinfo=utc)
utc_now # Timezone-aware.
local_now = utc_now.astimezone(local)
Dates don't exist in isolation. It is common that you will need to find the amount of time between
dates or
determine what the date will be tomorrow. This can be accomplished using timedelta objects
import datetime
today = datetime.date.today()
print('Today:', today)
print('Yesterday:', yesterday)
print('Tomorrow:', tomorrow)
print('Time between tomorrow and yesterday:', tomorrow - yesterday)