Date and Time
Dates and Times
First, a quick review of time and clocks wrt GNU/Linux:
- Epoch time is the number of seconds since 1970-01-01 00:00:00 UTC. Aka “timestamp” or “unix time”.
- DST (daylight savings time) adjustments are only made to local time, not to UTC. So, your local time may be a differing number of hours off from UTC depending upon what time of year it is (that is, whether or not DST is in effect).
- The hwclock (BIOS), aka RTC (real time clock) is separate from the system (OS) clock. Regular GNU/Linux machines have their hardware clock set to UTC.
- When you boot up, your OS system clock gets its time from the hwclock, and your OS knows your timezone and whether or not DST is in effect.
- You need root access to run the hwclock command. Note that by default
hwclock
shows h/w clock time in local time, even though it’s set to UTC.
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:
- seconds since epoch (a float)
- “time-tuple” (tuple of 9 integers)
- human-readable date/time string
A time-tuple has fields:
- tm_year (integer year)
- tm_mon (1–12)
- tm_mday (1–31)
- tm_hour (0–23)
- tm_min (0–59)
- tm_sec (0–61, to cover leap-seconds)
- tm_wday (0–6, Mon == 0)
- tm_yday (1–366)
- tm_isdst (-1 == library determines dst, 0 == no, 1 == yes)
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
'2018-04-16', '%Y-%m-%d') #=> corresponding time-tuple time.strptime(
Sleep
import time
3) # 3 seconds time.sleep(
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.