Dealing with Datetimes

Paul Ganssle


Introduction

Overview

  • Time Zones
  • Serializing and deserializing datetimes
  • Recurring events

Datetime Basics: Absolute vs. Civil Times

  • Absolute times ("timestamps"): A specific moment in time
    • Usually the right choice for times in the past (logs, etc)
    • Store as UTC or fixed offset


  • Civil times ("wall times"): The time it says on the clock in a given place
    • Usually the right choice for times in the future (meetings, alarms, etc)
    • Store as local time (+ time zone)

Datetime Basics: datetime.datetime

datetimes are immutable

In [2]:
dt = datetime(2019, 5, 1, 13)
try:
    dt.year = 2020
except Exception as e:
    print(repr(e))
AttributeError("attribute 'year' of 'datetime.date' objects is not writable")

Use the replace method to get a new datetime with one or more properties modified:

In [3]:
dt.replace(year=2020)
Out[3]:
datetime.datetime(2020, 5, 1, 13, 0)
In [4]:
dt.replace(year=2020, minute=30)
Out[4]:
datetime.datetime(2020, 5, 1, 13, 30)

Datetime Basics: datetime.timedelta

  • Represents the difference between two "wall times"
  • Does not represent total elapsed time between two times
In [5]:
from datetime import timedelta
In [6]:
dt_dst = datetime(2019, 11, 2, 12, tzinfo=tz.gettz("America/New_York"))
dt_std = dt_dst + timedelta(hours=24)
print(dt_dst)
print(dt_std)
2019-11-02 12:00:00-04:00
2019-11-03 12:00:00-05:00
In [7]:
print(dt_std.astimezone(tz.UTC) - dt_dst.astimezone(tz.UTC))
1 day, 1:00:00

Datetime Basics: Aware vs. Naive datetimes

  • Naive datetime: No time zone information
  • Aware datetime: Localized to a specific time zone
In [8]:
print(datetime(2019, 5, 1, 13))
2019-05-01 13:00:00
In [9]:
print(datetime(2019, 5, 1, 13, tzinfo=tz.gettz("America/New_York")))
2019-05-01 13:00:00-04:00

Break

Take a 15 minute break!

Back at:

Q & A