Skip to content

Instantly share code, notes, and snippets.

@spatialtime
Created May 12, 2020 16:18
Show Gist options
  • Save spatialtime/cf5431a685fbbde1d7d8d050ec22c1e1 to your computer and use it in GitHub Desktop.
Save spatialtime/cf5431a685fbbde1d7d8d050ec22c1e1 to your computer and use it in GitHub Desktop.
Pythonic formatting and parsing of ISO 8601 dates, times, and time zones.
# This snippet demonstrates Pythonic formatting and parsing of ISO 8601 dates.
from datetime import datetime
# datetime.strptime() is used to parse iso 8601 strings to
# Python datetime.datetime instances.
# datetime.strftime() is used to format Python datetime.datetime instances
# to ISO 8601 strings.
# Note: the built-in function, format() calls datetime.strftime().
# YYYY
d = datetime.strptime("2020", "%Y")
print(format(d, "%Y"))
# YYYY-MM
d = datetime.strptime("2020-05", "%Y-%m")
print(format(d, "%Y-%m"))
# YYYY-MM-DD
d = datetime.strptime("2020-05-03", "%Y-%m-%d")
print(format(d, "%F"))
# Note: the shortcut %F directive is supported by strftime(),
# but not strptime()!
# hh:mm
d = datetime.strptime("13:15", "%H:%M")
print(format(d, "%R"))
# Note: the shortcut %R directive is supported by strftime(),
# but not strptime()!
# hh:mm:ss
d = datetime.strptime("13:15:45", "%H:%M:%S")
print(format(d, "%T"))
# Note: the shortcut %T directive is supported by strftime(),
# but not strptime()!
# hh:mm:ss.sss
d = datetime.strptime("13:15:45.321", "%H:%M:%S.%f")
print(format(d, "%T.%f")[:-3])
# hh:mm:ssZ (zulu time)
d = datetime.strptime("13:15:45", "%H:%M:%S")
print(format(d, "%H:%M:%SZ"))
# Create a datetime for time zone formats below.
d = datetime.strptime("13:15:45-08:30", "%H:%M:%S%z")
# Have to do a little work here to achieve time zone offsets with either
# Simple hh (hours only) or the extended hh:mm format.
s = format(d, "%T%z")
s1 = s[:11]
s2 = s[11:]
# hh:mm:ss±hh
print(s1)
# hh:mm:ss±hh:mm
print(s1+":"+s2)
# YYYY-MM-DDThh:mm:ss-hh:ss (full date/time/time zone)
d = datetime.strptime("2020-05-03T13:15:45-08:30", "%Y-%m-%dT%H:%M:%S%z")
print(format(d, "%F") + "T" + s1 + ":" + s2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment