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()}")
print(f"utcnow = {datetime.datetime.utcnow()}")
Better yet, instead of "import datetime" you can go with from datetime import datetime so that you can use datetime.xxx() instead of datetime.datetime.xxx().
#!/usr/bin/python3
from datetime import datetime
print(f"today = {datetime.today()}")
print(f"now = {datetime.now()}")
print(f"utcnow = {datetime.utcnow()}")
Running this script will return something like this.
today = 2023-02-09 21:34:36.025655
now = 2023-02-09 21:34:36.025713
utcnow = 2023-02-10 03:34:36.025733
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 |
The pytz (Python Time Zone) module can be used to include time zone. You will probably need to use pip to install pytz.
pip install pytz
Then astimezone() and %z and %Z can be used to include the time zone.
#!/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)
Did you find this article helpful?
If so, consider buying me a coffee over at