How to get the current day, month, and / or year in python
You want the current day or year? Sometimes dates and times are tough—to format, to work with, to get. Let's make this as easy as possible.
Using datetime
The datetime
module is my go-to Python library for working with dates and times. To get the day, month, and year is as simple as using the .now()
method and then grabbing the attributes you want:
#! python3
# How to get the current day, month, and year in python
from datetime import datetime as dt
# Capture current date/time
timestamp = dt.now()
# Print month, day, and year attributes from our timestamp
print(f"Month: {timestamp.month}")
print(f"Day: {timestamp.day}")
print(f"Year: {timestamp.year}")
In case you're unfamiliar, the import statement
from datetime import datetime as dt
is setting dt
as an alias (or another name) for datetime
. I'm doing this just because it shortens the amount of typing I have to do. If you take off the as dt
part of the line, you'll just have to write out datetime
wherever you see dt
.Notes on Timezones
It's important to recognize that the code above gives you the day, month, and year in the local timezone. If you need these to be in a specific timezone, you can use the pytz
library to make your timestamp timezone-aware.
#! python3
# How to get the current, timezone-aware day, month, and year in python
from datetime import datetime as dt
import pytz
# Use a variable to store your timezone
new_york_timezone = pytz.timezone('America/New_York')
# Get the current timestamp in the timezone
timestamp = dt.now(new_york_timezone)
# Print month, day, and year attributes from our timestamp
print(f"Month: {timestamp.month}")
print(f"Day: {timestamp.day}")
print(f"Year: {timestamp.year}")
Ignoring timezones can have big consequences, like incorrect calculations or information—especially when dealing with international applications. You don't want to accidentally close off customers a day early, just because they're in a different timezone, for example.
Is pytz
on its way out? What are alternatives?
It seems like this library gets some flack, and surely it's justified if you're doing something more complicated with timezones. I haven't used this myself, but I know Pendulum is a common recommendation as a pytz
alternative that seems pretty easy to use.
ZoneInfo for Python 3.9+
If you prefer as few third-party libraries as possible and you're on python 3.9+, you can also use the new zoneinfo
library. Our code stays pretty consistent, just swapping pytz.timezone
with ZoneInfo(...)
:
#! python3
# Alternate for python 3.9+
# How to get the current, timezone-aware day, month, and year in python
from datetime import datetime as dt
from zoneinfo import ZoneInfo
# Replace 'UTC' with the desired timezone
tz = ZoneInfo('UTC')
timestamp = dt.now(tz)
# Print month, day, and year attributes from our timestamp
print(f"Month: {timestamp.month}")
print(f"Day: {timestamp.day}")
print(f"Year: {timestamp.year}")