- Published on
Python Common Date and Time Cases
Prerequisites
You can use any python interpreter you want, such as native python script in your local machine, anaconda/jupyter
notebook, or even google colab
. We are going to use the built-in library datetime
in python, here is the initial library import for the cases:
from datetime import datetime
from datetime import timedelta
and any date and time formatting refers to the official docs.
Getting the current date and time of the local server (and its timezone)
Getting standard date and time
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Getting the partial values of date and time
# creating today object
today = datetime.now()
# getting current year
print(today.year)
# getting current month (number)
print(today.month)
# getting current day of month (number)
print(today.day)
# getting current day of week (number)
print(today.weekday())
# getting current day of year (number)
print(today.strftime("%j"))
Getting the UNIX timestamp
int(datetime.now().timestamp())
Getting the current UTC date and time
If your machine is set in a different timezone other than UTC, you can get the UTC date and time by:
datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
or getting the UNIX timestamp of the current UTC date and time:
int(datetime.utcnow().timestamp())
Parsing a certain date string format
parsing 2022-08-04 04:23:51
:
certain_datetime = datetime.strptime("2022-08-04 04:23:51", "%Y-%m-%d %H:%M:%S")
print(certain_datetime.year)
print(certain_datetime.month)
print(certain_datetime.day)
print(certain_datetime.hour)
print(certain_datetime.minute)
print(certain_datetime.second)
parsing May 8, 2003
:
certain_datetime = datetime.strptime("May 8, 2003", "%b %d, %Y")
print(certain_datetime.year)
print(certain_datetime.month)
print(certain_datetime.day)
print(certain_datetime.hour)
print(certain_datetime.minute)
print(certain_datetime.second)
Get differences between two DateTime
Getting days and second differences between 2021-04-01 11:43:41
and 2022-08-05 04:23:51
date1 = datetime.strptime("2021-04-01 11:43:41", "%Y-%m-%d %H:%M:%S")
date2 = datetime.strptime("2022-08-05 04:23:51", "%Y-%m-%d %H:%M:%S")
diff = date2 - date1
print('difference in days:', diff.days)
print('difference in seconds:', diff.seconds)