» Quick Introduction to Python » 4. Common Modules » 4.2 datetime

datetime

The datetime module supplies classes for manipulating dates and times.

Get Current Datetime

from datetime import datetime

print(datetime.now()) # YYYY-mm-DD HH:MM:SS.023000

# with spcific timezone
import pytz

tz = pytz.timezone("America/New_York")
print(datetime.now(tz)) # YYYY-mm-DD HH:MM:SS.023000

Format Datetime

from datetime import datetime

nw = datetime.utcfromtimestamp(1629489987.567)
print(nw)
print(nw.strftime('Weekday long version  : %A'))
print(nw.strftime('Weekday short version : %a'))
print(nw.strftime('Weekday as a number   : %w'))
print(nw.strftime('Month long version    : %b'))
print(nw.strftime('Month short version.  : %d'))
print(nw.strftime('Month as a number     : %m'))
print(nw.strftime('Year long version     : %Y'))
print(nw.strftime('Year short version    : %y'))
print(nw.strftime('Day of the month      : %d'))
print(nw.strftime('Hour (24Hrs)          : %H'))
print(nw.strftime('Hour (12Hrs)          : %I'))
print(nw.strftime('AM / PM               : %p'))
print(nw.strftime('Minute                : %M'))
print(nw.strftime('Second                : %S'))
print(nw.strftime('%a %d-%m-%Y'))
print(nw.strftime('%a %m/%d/%Y'))
print(nw.strftime('%a %d/%m/%y'))
print(nw.strftime('%A %m-%d-%Y, %H:%M:%S'))
print(nw.strftime('%X %x'))

The output looks like this:

2021-08-20 20:06:27.567000
Weekday long version  : Friday
Weekday short version : Fri
Weekday as a number   : 5
Month long version    : Aug
Month short version.  : 20
Month as a number     : 08
Year long version     : 2021
Year short version    : 21
Day of the month      : 20
Hour (24Hrs)          : 20
Hour (12Hrs)          : 08
AM / PM               : PM
Minute                : 06
Second                : 27
Fri 20-08-2021
Fri 08/20/2021
Fri 20/08/21
Friday 08-20-2021, 20:06:27
20:06:27 08/20/21

Convert String to Datetime

from datetime import datetime

dt = datetime.fromisoformat("2017-05-20 10:26:45")
print(dt) # 2017-05-20 10:26:45
print(nw.strftime('%a %m/%d/%Y')) # Fri 08/20/2021
print(nw.strftime('%A %m-%d-%Y, %H:%M:%S')) # Friday 08-20-2021, 20:06:27

from datetime import time
t = time.fromisoformat("15:58:21")
print(t.strftime('%I:%M %p')) # 03:58 PM

Time Delta

A timedelta object represents a duration, the difference between two dates or times.

from datetime import timedelta

delta = timedelta(
    days=50,
    seconds=27,
    microseconds=10,
    milliseconds=29000,
    minutes=5,
    hours=8,
    weeks=2
)
# Only days, seconds, and microseconds remain
print(repr(delta)) # datetime.timedelta(days=64, seconds=29156, microseconds=10)
print(delta) # 64 days, 8:05:56.000010

Code Challenge

Try to modify the code in the editor to make it print {'days': 2, 'hours': 3, 'minutes': 30, 'seconds': 0}.

Loading...
> code result goes here
Prev
Next