Python Notes and Examples

Date and Time

Dates and Times

First, a quick review of time and clocks wrt GNU/Linux:

To see more details of what your h/w and system clocks are set to:

$ timedatectl      # Shows various info about your clocks.
# hwclock --debug  # More info.
$ date +%s   # unix/posix/epoch time
$ date       # human-readable, local
$ date -u    # human-readable, UTC

The upshot of all this is: store your times in epoch time. You can always convert them later to a local time for displaying them.

Python Dates and Times

The time module

Python uses a handful of different time formats, including:

A time-tuple has fields:

Recall that DST is on (== 1) after you spring ahead and until you fall back.

To convert between Python’s basic time formats, see these functions in the time module:

Ex:

import time
time.strptime('2018-04-16', '%Y-%m-%d')  #=> corresponding time-tuple

Sleep

import time
time.sleep(3)  # 3 seconds

The datetime module

The main classes in the datetime module are: date, time, datetime, timedelta, and timezone. Times and datetimes can be naive (of tz info) or aware. Dates are always naive.

See the docs for datetime.