2.3 time and dateandtime
Contents
Note
Click here to download the full example code or to run this example in your browser via Binder
2.3 time and dateandtime#
Important
This lesson is still under development.
time#
import time
time()
1731311822.0541122
7.486343383789062e-05 seconds
sleep()
for i in range(5):
time.sleep(0.5)
print(i, end = " ")
0 1 2 3 4
asctime()
'Mon Nov 11 07:57:04 2024'
clock()
daylight
localtime()
print(time.localtime())
time.struct_time(tm_year=2024, tm_mon=11, tm_mday=11, tm_hour=7, tm_min=57, tm_sec=4, tm_wday=0, tm_yday=316, tm_isdst=0)
timezone
ctime()
print(time.ctime())
Mon Nov 11 07:57:04 2024
datetime#
from datetime import datetime
datetime.now()
2024-11-11 07:57:04.559395
print(type(now))
<class 'datetime.datetime'>
datetime.ctime()
datetime.ctime(now)
'Mon Nov 11 07:57:04 2024'
datetime.strftime()
print(datetime.strftime(now, "%Y-%m-%d %H:%M:%S"))
2024-11-11 07:57:04
datetime.strptime()
datetime.isoformat()
datetime.isoformat(now)
'2024-11-11T07:57:04.559395'
datetime.isoformat(now, sep=" ")
'2024-11-11 07:57:04.559395'
datetime.fromisoformat()
datetime.toordinal()
datetime.fromtimestamp()
timedelta#
datetime.datetime(2024, 11, 11, 7, 57, 14, 561237)
datetime.datetime(2024, 11, 21, 7, 57, 4, 561237)
datetime.datetime(2025, 1, 20, 7, 57, 4, 561237)
datetime.datetime(2024, 11, 10, 21, 57, 4, 561237)
We can compare two datetime objects
True
False
True
False
strftime()
now.strftime("%Y%m%d_%H%M%S")
'20241111_075704'
now.strftime("%d %B %Y %H:%M:%S")
'11 November 2024 07:57:04'
Total running time of the script: ( 0 minutes 2.510 seconds)