Introduction
Working with dates and times in any programming language can be a huge hassle. There are so many ways to mess up when using different date and time formats, dealing with timezones, and accounting for daylight savings time. There are a lot of things to remember to get right. I'll show you everything you need to know about working with dates and times in Python to make it easy so you can feel confident any time you have work with them.
Video
How to get the current time
Let's start with how to get the current time. Before we get the current time though, we need to know what format we want to get the date. In Python, there are two main ways of handling time. You can either use a Unix timestamp or a Python DateTime object Let's look at the differences between the two.
Unix Timestamp
- Unix timestamp is number of seconds since Unix epoch January 1, 1970 UTC
- It is usually an integer but can be a floating point number if system has millisecond or greater time resolution
- It is convenient because it's easy and efficient to store and compare an integer or floating point number versus a long string
- The drawback is that it is difficult for a human to read and is always in UTC timezone. Typically, you will store your times in this format but convert it to a human-readable format when outputting it to a user.
I recommend using a Unix timestamp to store your times if you are using a database.
https://docs.python.org/3/library/time.html
Datetime object
This is a more complex object datetime object that stores detailed year, month, day, time, and timezone information It has methods to convert to and from a Unix timestamp and to format the output. It can also store timezone information although by default it is a naive time object which means it doesn't know anything about timezones. There is a date and a time object in the package that can be used separately but I'm only going to talk about the combination datetime object.
https://docs.python.org/3/library/datetime.html#datetime-objects
Converting between Unix timestamp and Python DateTime objects
- Datetime objects can be converted to a Unix timestamp with the
timestamp()
method on a Datetime object - Datetime objects can be created from a Unix timestamp with the
fromtimestamp()
function from thedatetime
module
Formatting output
Like I mentioned earlier, you will often store the times as Unix timestamps and format them on output.
You'll need a datetime object for all of these, so call fromtimestamp()
first if you need to get a datetime
object from a Unix timestamp.
Get time delta between two events
To measure how long something takes, follow these steps:
- Store current time
- Perform some time-consuming action
- Store the time it finishes
- Calculate the difference between the start and finish times - https://docs.python.org/3/library/datetime.html#timedelta-objects
from datetime import datetime
from time import sleep
start_time = datetime.now()
sleep(2)
end_time = datetime.now()
time_difference = end_time - start_time
print(type(time_difference)) # <class 'datetime.timedelta'>
print(time_difference)
print(time_difference.total_seconds())
Examples
from time import time, sleep
from datetime import datetime, timedelta
"""
Get current time
"""
# Get current time as Unix timestamp
unix_timestamp_now = time()
print(f'Unix time: {unix_timestamp_now}')
# Get current time as DateTime object
datetime_now = datetime.now()
print(f'Datetime now: {datetime_now} {type(datetime_now)}')
"""
Convert between timestamp and datetime objects
"""
# Get Unix timestamp from a datetime object
datetime_unix_time = datetime.now().timestamp()
print(f'Datetime as unix timestamp: {datetime_unix_time}')
# Convert timestamp to datetime object
datetime_from_unix_time = datetime.fromtimestamp(time())
print(f'DateTime from Unix timestamp: {datetime_from_unix_time}')
# Get datetime object from string
print('Dates parsed from strings')
print(datetime.strptime('2020-06-18', '%Y-%m-%d'))
print(datetime.strptime('2020-06-18 12:30:00', '%Y-%m-%d %H:%M:%S'))
"""
Formatting output
"""
# Format date output
formatted_date = datetime_now.strftime('%A %B, %-d, %Y %-H:%M %p %Z')
print(f'Formatted date: {formatted_date}') # E.g. Sunday June, 14, 2020 3:17 AM
# Get ISO 8601 format string
# https://en.wikipedia.org/wiki/ISO_8601
# https://strftime.org
iso_date_with_microseconds = datetime_now.strftime('%Y-%m-%dT%H:%M:%S.%fZ%z')
print(f'ISO 8601 date format with microseconds: {iso_date_with_microseconds}')
iso_date_without_microseconds = datetime_now.strftime('%Y-%m-%dT%H:%M:%S.%fZ%z')
print(f'ISO 8601 date format w/o microseconds: {iso_date_with_microseconds}')
easy_iso_format = datetime_now.isoformat() # Will include microseconds
print(f'ISO 8601 date format: {easy_iso_format}')
"""
Time zones
"""
# The best way to handle timezones is to use `pytz` module and call localize
# pip install pytz
import pytz
timezone = pytz.timezone('America/Chicago')
local_time = timezone.localize(datetime.now())
print(f"Local time ISO: {local_time.isoformat()}")
print(f"Local time friendly: {local_time.strftime('%A %B, %-d, %Y %-H:%M %p %Z')}")
"""
Get future/past times
"""
three_days_ago = datetime.now() - timedelta(days=3)
print(f'Three days ago: {three_days_ago}')
"""
Calculate delta between times
"""
delta = datetime.now() - three_days_ago
print(f'Time delta: {delta} - Days: {delta.days}, Seconds: {delta.seconds}')
print(f'Time delta total seconds: {delta.total_seconds()}')
benchmark_start_time = datetime.now()
sleep(1)
benchmark_end_time = datetime.now()
duration = benchmark_end_time - benchmark_start_time
print(duration)
print(duration.total_seconds())
Conclusion
After reading through this guide you should have a better understanding of how to work with dates and time objects in Python 3 and how to convert, format, calculate time differences, localize time zones, and parse times.