Time in Python

Python offers extensive support for times and durations; here are some examples.

import datetime
import pytz

def main():
    p = print

    # We'll start by getting the current time.
    now = datetime.datetime.now(pytz.UTC)
    p(now)

    # You can build a datetime object by providing the
    # year, month, day, etc. Times are always associated
    # with a timezone.
    then = datetime.datetime(2009, 11, 17, 20, 34, 58, 651387, pytz.UTC)
    p(then)

    # You can extract the various components of the time
    # value as expected.
    p(then.year)
    p(then.month)
    p(then.day)
    p(then.hour)
    p(then.minute)
    p(then.second)
    p(then.microsecond)
    p(then.tzinfo)

    # The Monday-Sunday weekday is also available.
    p(then.strftime("%A"))

    # These methods compare two times, testing if the
    # first occurs before, after, or at the same time
    # as the second, respectively.
    p(then < now)
    p(then > now)
    p(then == now)

    # The subtraction operation returns a timedelta representing
    # the interval between two times.
    diff = now - then
    p(diff)

    # We can compute the length of the duration in
    # various units.
    p(diff.total_seconds() / 3600)  # hours
    p(diff.total_seconds() / 60)    # minutes
    p(diff.total_seconds())         # seconds
    p(diff.total_seconds() * 1e9)   # nanoseconds

    # You can use addition to advance a time by a given
    # duration, or with a negative value to move backwards by a
    # duration.
    p(then + diff)
    p(then - diff)

if __name__ == "__main__":
    main()

To run the program, save it as time_example.py and use python:

$ python time_example.py
2023-05-31 10:15:30.123456+00:00
2009-11-17 20:34:58.651387+00:00
2009
11
17
20
34
58
651387
UTC
Tuesday
True
False
False
4942 days, 13:40:31.472069
118620.50873725626
7117230.524235375
427033831.4541225
427033831454122.5
2023-05-31 10:15:30.123456+00:00
1996-05-05 06:54:27.179318+00:00

In this Python example, we use the datetime module for time operations and pytz for timezone support. The timedelta class is used for duration calculations.

Note that Python’s datetime doesn’t have nanosecond precision (it goes up to microseconds), so we simulate nanoseconds by multiplying seconds by 1e9.

The strftime method is used to format the date as a string, which we use to get the weekday name.

Python’s comparison operators (<, >, ==) work directly on datetime objects, making time comparisons straightforward.

Next, we’ll look at the related idea of time relative to the Unix epoch.