# Import module
from datetime import datetime, timedelta
16 Working with dates and times
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
Basic datetime
Syntax
# Current date and time
= datetime.now()
now print(type(now)) # show data type
print("Current Date and Time:", now)
# Specific date and time
= datetime(2022, 4, 15, 8, 30)
planting_date print("Planting Date and Time:", planting_date.strftime('%Y-%m-%d %H:%M:%S'))
# Parsing String to Datetime
= datetime.strptime("2022-09-15 14:00:00", '%Y-%m-%d %H:%M:%S')
harvest_date 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
= harvest_date - planting_date
duration 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
= planting_date + timedelta(days=10)
emergence_date 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
= pd.DataFrame({
df "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
'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')
df[
# Add a timedelta column
'growing_season_length'] = df['harvest_dates'] - df['planting_dates']
df[
# 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 |