
datetime can be used to work with date and time in a Python script. Take for example the following.
#!/usr/bin/python3
import datetime
print(f"today = {datetime.datetime.today()}")
print(f"now = {datetime.datetime.now()}")
Better yet, instead of "import datetime" you can go with from datetime import datetime so that you can use datetime.now() or datetime.today() instead of datetime.datetime.now() or datetime.datetime.today().
#!/usr/bin/python3
from datetime import datetime
print(f"today = {datetime.today()}")
print(f"now = {datetime.now()}")
Running this script will return something like this.
today = 2023-02-09 21:34:36.025655
now = 2023-02-09 21:34:36.025713
date() and time() can be included to only get the date or time.
#!/usr/bin/python3
from datetime import datetime
print(f"today date = {datetime.today().date()}")
print(f"today time = {datetime.today().time()}")
Which should print something like this.
today date = 2023-02-09
today time = 21:34:36.025706
Often, when issuing a request to a REST API, the response timestamp should be a string.
#!/usr/bin/python3
response = requests.get("https://example.com/api/v1")
timestamp = response['timestamp']
Or, when submitting a query to a SQL database, timestamp may be a string or a datetime object.
#!/usr/bin/python3
import psycopg2
connection = psycopg2.connect(database=db_name, host=db_host, user=db_user, password=db_pass, port=db_port)
cursor = connection.cursor()
cursor.execute("select timestamp from mytable")
results = cursor.fetchall()
for row in results:
timestamp = row[0]
cursor.close()
connection.close()
type can be used to determine if the timestamp object is a string or boolean or datetime object, et cetera.
print(f"timestamp type = {type(timestamp)}")
If the timestamp object is not a datetime object, strptime can be used to convert the object into a datetime object so that you can do something with the datetime object.
#!/usr/bin/python3
datetime_object = datetime.strptime("2023-07-02 07:14:58", "%Y-%m-%d %H:%M:%S")
print(f"datetime_object = {datetime_object}")
strftime can be used for a customized date and time format.
#!/usr/bin/python3
from datetime import datetime
print(f"formatted date time = {datetime.today().strftime("%m/%d/%Y %H:%M:%S")}")
Which should print the following.
formatted date time = 02/09/2023 06:24:10
Following are commonly used options.
Option | Description | Example |
---|---|---|
%Y | Year | 2018 |
%y | Year | 18 |
%m | Month | 01 |
%b | Month | Jan |
%B | Month | January |
%a | Short day of the week | Sun |
%A | Full day of the week | Sunday |
%d | Day (with leading zero) | 04 |
%-d | Day (without leading zero) | 4 |
%H | Hour (24 hour format) | 22 |
%I | Hour (12 hour format) | 10 |
%M | Minute | 56 |
%S | Second | 23 |
%s | Microseconds | 1677062390 |
%f | Microseconds | 508159 |
%p | AM or PM | AM |
%P | am or pm | pm |
Timezone
The pytz (Python Time Zone) module can be used if you need to set a specific timezone. You will probably need to use pip to install pytz.
pip install pytz
Here are a few examples of how you can use timezone.
#!/usr/bin/python3
from datetime import datetime
from pytz import timezone
print(f"utc = {datetime.now(timezone('utc'))}")
print(f"cst6cdt = {datetime.now(timezone('cst6cdt'))}")
print(f"america/chicago = {datetime.now(timezone('america/chicago'))}")
print(f"us/eastern = {datetime.now(timezone('us/eastern'))}")
print(f"asia/kolkata = {datetime.now(timezone('asia/kolkata'))}")
Or like this, using astimezone.
#!/usr/bin/python3
from datetime import datetime
from pytz import timezone
print(f"utc = {datetime.now().astimezone(timezone('utc'))}")
print(f"cst6cdt = {datetime.now().astimezone(timezone('cst6cdt'))}")
print(f"america/chicago = {datetime.now().astimezone(timezone('america/chicago'))}")
print(f"us/eastern = {datetime.now().astimezone(timezone('us/eastern'))}")
print(f"asia/kolkata = {datetime.now().astimezone(timezone('asia/kolkata'))}")
Which should return something like this.
utc = 2025-01-30 07:04:49.487889+00:00
cst6cdt = 2025-01-30 01:04:49.487931-06:00
america/chicago = 2025-01-30 01:04:49.497777-06:00
us/eastern = 2025-02-07 07:36:33.798807-05:00
asia/kolkata = 2025-01-30 12:34:49.498041+05:30
And here is an example of how you can take a string and convert it to a datetime object with timezone aware offset.
#!/usr/bin/python3
from datetime import datetime
import pytz
from pytz import timezone
print(f"utc = {pytz.utc.localize(datetime.strptime("02-10-2025 02:03:15", '%m-%d-%Y %H:%M:%S'))}")
print(f"cst6cdt = {pytz.utc.localize(datetime.strptime("02-10-2025 02:03:15", '%m-%d-%Y %H:%M:%S')).astimezone(timezone('cst6cdt'))}")
print(f"america/chicago = {pytz.utc.localize(datetime.strptime("02-10-2025 02:03:15", '%m-%d-%Y %H:%M:%S')).astimezone(timezone('america/chicago'))}")
print(f"us/eastern = {pytz.utc.localize(datetime.strptime("02-10-2025 02:03:15", '%m-%d-%Y %H:%M:%S')).astimezone(timezone('us/eastern'))}")
print(f"asia/kolkata = {pytz.utc.localize(datetime.strptime("02-10-2025 02:03:15", '%m-%d-%Y %H:%M:%S')).astimezone(timezone('asia/kolkata'))}")
Which should return something like this.
utc = 2025-02-10 02:03:15+00:00
cst6cdt = 2025-02-09 20:03:15-06:00
america/chicago = 2025-02-09 20:03:15-06:00
us/eastern = 2025-02-09 21:03:15-05:00
asia/kolkata = 2025-02-10 07:33:15+05:30
If you simply just want to be able to use %z or %Z in strftime, astimezone can be used.
#!/usr/bin/python3
from datetime import datetime
import pytz
print(f"time zone offset = {datetime.now().astimezone().strftime("%m/%d/%Y %H:%M:%S %z")}")
print(f"time zone = {datetime.now().astimezone().strftime("%m/%d/%Y %H:%M:%S %Z")}")
Which should return something like this.
time zone offset = 05/25/2023 02:23:57 -0500
time zone = 05/25/2023 02:23:57 CDT
Here is how you can return the date and time in a specific time zone.
#!/usr/bin/python
from datetime import datetime
import pytz
from pytz import timezone
print("datetime.now(timezone('Asia/Kolkata')))
print("datetime.now(timezone('America/Chicago')))
print("datetime.now(timezone('CST6CDT')))
Here is how you can print the timezones that can be used with pytz.
#!/usr/bin/python
import pytz
for timezone in pytz.all_timezones:
print(timezone)
relativedelta can be used to adjust the date forward or backwards. You will need to install the python-dateutil package to use relativedelta.
pip install python-dateutil
Here are some examples.
#!/usr/bin/python
from datetime import datetime
from dateutil.relativedelta import relativedelta
one_hour_ago = datetime.now() - relativedelta(hours=1)
one_day_ago = datetime.now() - relativedelta(days=1)
one_week_ago = datetime.now() - relativedelta(weeks=1)
one_month_ago = datetime.now() - relativedelta(months=1)
one_year_ago = datetime.now() - relativedelta(years=1)
Here is how you can use both relativedelta and strftime.
#!/usr/bin/python
from datetime import datetime
from dateutil.relativedelta import relativedelta
one_hour_ago = (datetime.now() - relativedelta(hours=1)).strftime('%m/%d/%Y')
one_day_ago = (datetime.now() - relativedelta(days=1)).strftime('%m/%d/%Y')
one_week_ago = (datetime.now() - relativedelta(weeks=1)).strftime('%m/%d/%Y')
one_month_ago = (datetime.now() - relativedelta(months=1)).strftime('%m/%d/%Y')
one_year_ago = (datetime.now() - relativedelta(years=1)).strftime('%m/%d/%Y')
Here is an if statement that can be used to convert a day such as 1 to 1st or 2 to 2nd or 3 to 3rd or 4 to 4th.
if re.match('^(1|21|31)$', datetime.now().strftime('%-d')):
day = f"{datetime.now().strftime('%-d')}st"
elif re.match('^(2|22)$', datetime.now().strftime('%-d')):
day = f"{datetime.now().strftime('%-d')}nd"
elif re.match('^(3|23)$', datetime.now().strftime('%-d')):
day = f"{datetime.now().strftime('%-d')}rd"
else:
day = f"{datetime.now().strftime('%-d')}th"
Here is how to return a specific day, such as daylight savings (first Sunday in November).
current_year = datetime.today().strftime("%Y")
november_first = datetime.strptime(f"11-01-{current_year}", "%m-%d-%Y")
integer = 1
match = False
while (match != True):
day_of_the_week = november_first.strptime(f"11-0{integer}-{current_year}", "%m-%d-%Y").strftime("%A")
if day_of_the_week == "Sunday":
daylight_savings = datetime.strptime(f"11-0{integer}-{current_year}", "%m-%d-%Y").strftime("%m-%d-%Y")
break
else:
integer += 1
now = datetime.now()
# override for testing/debugging/proof of concept
#now = datetime.strptime("2024-11-03", "%Y-%m-%d")
if now == datetime.strptime(f"{daylight_savings}", "%m-%d-%Y %H"):
print(f"Today {daylight_savings} is daylight savings")
else:
print(f"Today {daylight_savings} is NOT daylight savings")
Did you find this article helpful?
If so, consider buying me a coffee over at