Time Formatting Parsing in Python

Python supports time formatting and parsing via the datetime module and the strftime and strptime functions.

from datetime import datetime
import time

def p(arg):
    print(arg)

# Here's a basic example of formatting a time
# according to ISO 8601 (similar to RFC3339)
t = datetime.now()
p(t.isoformat())

# Time parsing uses the same format strings as strftime
t1 = datetime.strptime("2012-11-01T22:08:41+00:00", "%Y-%m-%dT%H:%M:%S%z")
p(t1)

# strftime and strptime use format codes. You can also
# supply custom formats. The codes must match the
# components of the time you want to format/parse.

p(t.strftime("%I:%M%p"))
p(t.strftime("%a %b %d %H:%M:%S %Y"))
p(t.strftime("%Y-%m-%dT%H:%M:%S.%f%z"))

form = "%I %M %p"
t2 = datetime.strptime("8 41 PM", form)
p(t2)

# For purely numeric representations you can also
# use standard string formatting with the extracted
# components of the time value.
print("{:d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}-00:00".format(
    t.year, t.month, t.day,
    t.hour, t.minute, t.second))

# strptime will raise a ValueError on malformed input
# explaining the parsing problem.
try:
    datetime.strptime("8:41PM", "%a %b %d %H:%M:%S %Y")
except ValueError as e:
    p(str(e))

When you run this program, you’ll see output similar to this:

2023-04-15T18:00:15.161182+01:00
2012-11-01 22:08:41+00:00
06:00PM
Sat Apr 15 18:00:15 2023
2023-04-15T18:00:15.161182+0100
1900-01-01 20:41:00
2023-04-15T18:00:15-00:00
time data '8:41PM' does not match format '%a %b %d %H:%M:%S %Y'

In this Python example:

  1. We use the datetime module for handling dates and times.
  2. The strftime method is used for formatting times, similar to the Format method in the original example.
  3. The strptime function is used for parsing times, similar to the Parse function.
  4. Python uses format codes (like %Y, %m, %d) instead of the reference time used in the original example.
  5. Error handling is done using a try-except block, which catches and prints the ValueError that strptime raises on invalid input.

The concepts are similar, but the syntax and specific methods are adapted for Python. Python’s datetime module provides a robust set of tools for working with dates and times, offering functionality comparable to the time package in the original example.