4.1. Datetime Functionality#

The datetime module is fully described in the Python online documentation that you can access at Python Docs: datetime . We’ll begin by importing the three different portions of the module that we are going to use at various points throughout the book, datetime, timedelta, and time.

from datetime import datetime, timedelta, time

datetime objects#

Now let’s learn about and use the datetime objects from the datetime module. In meteorology we can’t concern ourselves with every local time zone, especially when various locations have daylight savings times and other locations don’t. As a result, meteorologists use a common time coordinate called Universal time (UTC or Zulu). This time never changes, there is no daylight savings time and it is the same at every location around the globe. To get the time in UTC

print(datetime.utcnow())
2024-08-30 15:22:15.311117

The following should be similar to the output that you see on your screen:

2020-01-01 21:53:38.422386

This is the default print format of the datetime object,

YYYY-MM-DD HH:MM:SS.ms

Now let’s save it to a variable name to be more useful:

now = datetime.utcnow()

The new variable we created (called now) is really so much more than simply holding the time; it is an object that contains various methods for access information from our stored computer time. For example, we may not want to use all of the information given in the default output from the date command, like we had above. Using the various methods and/or formatting statements will allow us to specify what information we want (e.g., year, month, day) and get its numeric or character value. Here are a couple of common methods for getting numeric elements out of our datetime object:

now.day

now.hour

now.minute

now.second

print(now)
print(now.year)
2024-08-30 15:22:15.317101
2024

To get a particular date format using the following list of format types (all begin with a percent sign; Python Docs: strftime-and-strptime-format-codes). Here we are going to do an example using the f-string (formatted string):

print(f'The current year is {now:%Y}')
The current year is 2024

You can combine the format statements to form strings, for example, write a Python print statement to get the year, month, and day in one continuous string (YYYYMMDD):

What is the result of the date function you wrote?



How about printing out the Month in a word abbreviation form?



Any of the Python statements given above can be assigned to a variable name to be used anywhere within your program. We’ll continue to come back to aspects of the datetime objects throughout the semester.

Set your own time#

We are not beholden to only using the current date/time – we can set any date/time we want. For example, let’s set a date of May 23, 2018 at 12 UTC, we can use the datetime module again by setting the the year, month, day, hour, minute, second.

Note

When setting your own time, the year, month, and day are required (in that exact order) and it no hour, minute, or second then they will be assumed to be zero.

# Set your own time
date = datetime(2018, 5, 23, 12)
print(date)
2018-05-23 12:00:00

timedelta objects#

There will be moments where you’ll want to do some math with the date (e.g., what time is 6 hours from now?) and timedelta objects makes that arithmatic very easy. Using the timedelta functionality we can add or substract days, seconds, microseconds, milliseconds, minutes, hours, or weeks.

Let’s try this out by finding what was the datetime 12 hours ago (subtraction) and what will it be two weeks from now (addition):

# 12 hours ago
print(now - timedelta(hours=12))
2024-08-30 03:22:15.317101

So above, we used our previously defined current time, now, and substracted using timedelta twelve hours. It was seamless for the combination of the datetime and timedelta objects to know that it had to role back one date in addition to subtracting the correct number of hours.

future_time = now + timedelta(weeks=2)
print(future_time)
2024-09-13 15:22:15.317101

Here we saved our time calculation to a new variable, future_time, and printed it out. Again, we let the computer do the hard work for us.

time objects#

The time objects deal with only the local time (hours, minutes, seconds, etc.) and are a subset of the datetime objects. We can use this to help us set a datetime object more efficiently when we may want to get a relatively current date, but set the hour to a specific time.

Let’s find the date of yesterday and set the time to 12 UTC.

# Use datetime and timedelta to get the date of yesterday
yesterday = datetime.utcnow() - timedelta(days=1)
print(yesterday)

# Use time to set a 12 UTC time
hour = time(12)
print(hour)

# Use the combine method to set a new datetime object
new_date = datetime.combine(yesterday, hour)
print(new_date)
2024-08-29 15:22:15.342631
12:00:00
2024-08-29 12:00:00