Dates, Times, and Timestamps in Python
The idea
You've already seen datetime in action — the Daily Notes project used it to timestamp every entry.
Now let's look at what it can actually do.
Importing datetime
from datetime import datetime, date, timedelta
The module is called datetime. The main class inside it is also called datetime. Import what you need specifically to keep things clean.
Getting the current date and time
from datetime import datetime
now = datetime.now()
print(now)
Output → 2024-05-06 14:32:45.123456
A datetime object — year, month, day, hour, minute, second, microsecond. All in one.
Access individual parts:
print(now.year) # 2024
print(now.month) # 5
print(now.day) # 6
print(now.hour) # 14
print(now.minute) # 32
Formatting — strftime()
strftime() converts a datetime object to a string in any format you want:
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2024-05-06
print(now.strftime("%d/%m/%Y")) # 06/05/2024
print(now.strftime("%Y-%m-%d %H:%M")) # 2024-05-06 14:32
print(now.strftime("%A, %d %B %Y")) # Monday, 06 May 2024
Common format codes:
%Y— 4-digit year%m— month (01–12)%d— day (01–31)%H— hour 24h (00–23)%M— minute (00–59)%A— full weekday name%B— full month name
Parsing — strptime()
strptime() converts a string into a datetime object — the reverse of strftime():
from datetime import datetime
date_str = "2024-05-06"
dt = datetime.strptime(date_str, "%Y-%m-%d")
print(dt.year) # 2024
print(dt.month) # 5
Useful when you read dates from a file or user input and need to work with them as datetime objects.
Date only — date
from datetime import date
today = date.today()
print(today) # 2024-05-06
print(today.weekday()) # 0 = Monday, 6 = Sunday
Time differences — timedelta
timedelta represents a duration — a difference between two dates or times:
from datetime import date, timedelta
today = date.today()
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(days=7)
print(tomorrow) # 2024-05-07
print(last_week) # 2024-04-29
You can also subtract two dates to get a timedelta:
from datetime import date
start = date(2024, 1, 1)
end = date(2024, 5, 6)
diff = end - start
print(diff.days) # 126
Heads up!
- The module and the main class have the same name —
from datetime import datetimeis correct strftime()— datetime to string.strptime()— string to datetimedatetime.now()includes time.date.today()is date only- Format codes are case-sensitive —
%Mis minutes,%mis month
What you should understand now
datetime.now()gives you the current date and timestrftime()formats a datetime as a stringstrptime()parses a string into a datetimedate.today()gives you today's date onlytimedeltaadds or subtracts days from a date