Working with Dates and Times#

Overview#

Working with dates and times in Python is a common task in geoscience workflows. This notebook will cover:

  • Working with the datetime module from the Python Standard Library

  • cftime, CF Conventions, and how they are related to working with geoscience data

  • A resource guide to point you to more detailed information depending on your use case

The datetime module#

From the module’s documentation:

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

import datetime

today = datetime.date.today()
print(f"datetime.date.today() -> \t {today}")
now = datetime.datetime.now()
print(f"datetime.datetime.now() -> \t {now}")
datetime.date.today() -> 	 2024-12-22
datetime.datetime.now() -> 	 2024-12-22 00:09:18.238175

strftime()#

You can use strftime() to parse and format these date objects.To see all formatting options, see the full list of format codes.

# print just the year
print("now.strftime('%Y')")
print(now.strftime("%Y"))
print()

# print weekday, month, day, year, 12h time, and AM/PM
print("now.strftime('%A, %B %d %Y %I:%M:%S %p')")
print(now.strftime("%A, %B %d %Y %I:%M:%S %p"))
print()

# use a shorter version to produce "locale appropriate" date and time
print("now.strftime('%c')")
print(now.strftime("%c"))
now.strftime('%Y')
2024

now.strftime('%A, %B %d %Y %I:%M:%S %p')
Sunday, December 22 2024 12:09:18 AM

now.strftime('%c')
Sun Dec 22 00:09:18 2024

These functions use a propeleptic Gregorian calendar, though, which is not always sufficient for working with geoscience data.

cftime#

cftime is another library for working with dates and times in Python that conforms to the Climate and Forecasting (CF) metadata conventions.

Importantly, cftime supports all the calendars defined in the CF conventions, including gregorian or standard, which is the mixed Gregorian/Julian calendar defined by Udunits, proleptic_gregorian, noleap or 365_day, all_leap or 366_day, 360_day, and julian.

cftime is often useful for working with geoscience data and can be used with xarray.

Specific Use Cases#

Calculating the number of days in a month#

To calculate the number of days in a month, use cftime.datetime().daysinmonth.

import cftime

day = 1
month = 6
year = 2024

date = cftime.datetime(year, month, day, calendar="standard").daysinmonth
date
30

Calculating the day of the week#

To calculate the day of the week, use cftime.datetime().strftime("%A").

import cftime

day = 4
month = 6
year = 2024

dow = cftime.datetime(
    year, month, day, calendar='proleptic_gregorian', has_year_zero=True
).strftime("%A")
print(f"{year}-{month}-{day} is a {dow}")
2024-6-4 is a Tuesday

Curated Resources#

To learn more about working with dates and times in Python, we suggest: