Dates and Times in Python


In this post I am illustrating just a few examples of dates and times to get us started. We also have another post here called Dates and Times in Pandas.

import datetime
dt = datetime.datetime(2024, 2, 27, 12, 40, 0)
print('datetime: {}'.format(dt))
print('datetime: {:%A, %m/%d/%Y %I:%M:%S %p}'.format(dt))
print('datetime: {}'.format(dt.isoformat()))

The output in Jupyter Notebook is:

datetime: 2024-02-27 12:40:00
datetime: Tuesday, 02/27/2024 12:40:00 PM
datetime: 2024-02-27T12:40:00

Now

# using now() to get current time 
current_time = datetime.datetime.now() 
ct = current_time
print(ct)

The output in Jupyter Notebook is:

2024-02-27 12:50:37.875493
print('The year is {}, month {}, day {}.'.format(ct.year, ct.month, ct.day))

The output in Jupyter Notebook is:

The year is 2024, month 2, day 27.
print('Hour {}, minute {}, second {} & microsecond {}'.format(ct.hour, ct.minute, ct.second, ct.microsecond))

The output in Jupyter Notebook is:

Hour 12, minute 50, second 37 & microsecond 875493

Leave a Reply