16  Working with dates and times

Author

Andres Patrignani

Published

January 10, 2024

Common tasks in crop and soil sciences usually require dealing with temporal information in the form of timestamps. Whether is the date a soil sample was collected, the day a crop was planted, or the timestamps recorded by dataloggers monitoring the weather, working with dates and times is a ubiquitous task in agronomy and related fields.

Python’s datetime module is an excellent and versatile tool for handling dates and times. Here, we’ll explore its syntax and functionality with practical examples.

List of shorthands to represent date and time components

%d = two-digit day
%m = two-digit month
%Y = two-digit year
%H = two-digit hour
%M = two-digit minute
%S = two-digit second
%b = three-letter month
%a = Three-letter day of the week
%A = Full day of the week

# Import module
from datetime import datetime, timedelta

Basic datetime Syntax

# Current date and time
now = datetime.now()
print(type(now)) # show data type
print("Current Date and Time:", now)

# Specific date and time
planting_date = datetime(2022, 4, 15, 8, 30)
print("Planting Date and Time:", planting_date.strftime('%Y-%m-%d %H:%M:%S'))

# Parsing String to Datetime
harvest_date = datetime.strptime("2022-09-15 14:00:00", '%Y-%m-%d %H:%M:%S')
print("Harvest Date:", harvest_date)

# We can also add custom datetime format in f-strings
print(f"Harvest Date: {harvest_date:%A, %B %d, %Y}")
<class 'datetime.datetime'>
Current Date and Time: 2024-01-12 16:56:03.399852
Planting Date and Time: 2022-04-15 08:30:00
Harvest Date: 2022-09-15 14:00:00
Harvest Date: Thursday, September 15, 2022

Working with timedelta

# Difference between two dates
duration = harvest_date - planting_date
print("Days Between Planting and Harvest:", duration.days)

# Total seconds of the duration
print("Total Seconds:", duration.total_seconds())

# Use total seconds to compute number of hours
print("Total hours:", round(duration.total_seconds()/3600), 'hours') # 3600 seconds per hour

# Adding ten days
emergence_date = planting_date + timedelta(days=10)
print("Crop emergence was on:", emergence_date)
Days Between Planting and Harvest: 153
Total Seconds: 13239000.0
Total hours: 3678 hours
Crop emergence was on: 2022-04-25 08:30:00

Using Pandas for datetime operations

# Import module
import pandas as pd
# Create a DataFrame with dates
df = pd.DataFrame({
    "planting_dates": ["2020-04-15", "2021-04-25", "2022-04-7"],
    "harvest_dates": ["2020-09-15", "2021-10-1", "2022-09-25"]
})

# Convert string to datetime in Pandas
df['planting_dates'] = pd.to_datetime(df['planting_dates'], format='%Y-%m-%d')
df['harvest_dates'] = pd.to_datetime(df['harvest_dates'], format='%Y-%m-%d')

# Add a timedelta column
df['growing_season_length'] = df['harvest_dates'] - df['planting_dates']

# Display dataframe
df.head()
planting_dates harvest_dates growing_season_length
0 2020-04-15 2020-09-15 153 days
1 2021-04-25 2021-10-01 159 days
2 2022-04-07 2022-09-25 171 days