Skip to content

Date and time

Peter Ebert edited this page Sep 22, 2022 · 1 revision
author date tags
PE 2022-08-23 cubi, internal, convention, rule, policy, standard

Date and timestamps

The only acceptable date and time format is described in the ISO 8601 standard.

Reference

In general, system time should be sufficient for timestamping in projects of the CUBI. If an authoritative reference is needed, the PTB time servers (ptbtimeN.ptb.de with N = {1, 2, 3}) should be used as trusted source.

If absolutely necessary, timezone deltas (time offset in hours, minutes etc.) must be stated relative to UTC time.

Summary

Acceptable formats include:

YYYY-MM-DD or YYYYMMDD (potentially preferable, e.g., in file names to avoid separator -) for dates: 2022-08-23

hh:mm:ss for the 24-hour clock system (12-hour clock system must not be used): 08:42:05 (numbers always zero-padded)

Timestamps combining date and time in a single string (e.g., in textual output tables) should use T as separator:

2022-08-23T08:42:05 - timestamps in that format cannot be part of a file name (due to the : separator), and should generally not be necessary because of the system timestamps of the file (atime, mtime and ctime).

Other information such as day of the year, calendar week or timezone information should only be used if absolutely necessary

Example code in Python

import sys
import datetime
print(sys.version)
# Python 3.8.13

# today's date
today_obj = datetime.date.today()
print(type(today_obj))
# <class 'datetime.date'>
today_str = today.strftime("%Y-%m-%d")
print(type(today_str))
# <class 'str'>
print(today_str)
# 2022-08-23

# full date and time
datetime_now = datetime.datetime.now()
# format as string
timestamp = datetime_now.strftime("%Y-%m-%dT%H:%M:%S")
print(timestamp)
# 2022-08-23T09:18:57

# year, calendar week, and day of week
year, cw, dow = today_obj.isocalendar()
print(year, cw, dow)
# 2022 34 2

# full timestamp including microseconds and UTC offset
full_ts_format = "%Y-%m-%dT%H:%M:%S.%f%z"
timestamp_full = datetime.datetime.now(datetime.timezone.utc).astimezone()
print(timestamp_full.strftime(full_ts_format))
# 2022-08-23T09:31:00.167378+0200
# local time zone
print(timestamp_full.tzinfo)
# CEST

input_dates = ["2022-12-04", "20221204"]
for d in input_dates:
    try:
        date_obj = datetime.date.fromisoformat(d)
    except ValueError:
        # string is not a valid [iso-formatted] date
        # using "-" as separator; this raises
        # for the second entry
        raise