Python datetime & time modules
Python provides two modules datetime
and time
to work with dates and time.
datetime - module¶
datetime
modules provides types likedatetime
- represents date and timedate
- only represents datetimedelta
- difference between two datetime values.time
- represents time onlytimezone
- fixed offset from UTC implementation of tzinfo.
create datetime object¶
from datetime import datetime
obj = datetime(
year=2022, month=11, day=1,
hour=23, minute=10, second=58,
microsecond=100
)
get current datetime¶
from datetime import datetime
now = datetime.now()
print(now)
# output: 2022-11-02 23:35:28.943015
- above program gives the current datetime
get current UTC datetime¶
from datetime import datetime
utc_now = datetime.utcnow()
print(utc_now)
# output: 2022-11-02 18:07:19.646767
datetime.utcnow()
gives current UTC datetime
get native indian time i.e UTC + 5:30¶
- we can use
datetime
andtimedelta
from dateime module
from datetime import datetime, timedelta
utc_now = datetime.utcnow()
ist_now = utc_now + timedelta(hours=5, minutes=30)
print(ist_now)
# output: 2022-11-02 23:44:02.068166
- we can also use timezone from
pytz
module
from pytz import timezone
from datetime import datetime
ist_now = datetime.now(timezone("Asia/Kolkata"))
print(ist_now)
# output: 2022-11-02 23:45:11.013421+05:30
convert datetime to "YYY-MM-DD HH:MM:SS"¶
- use
datetime.strftime
to get given format.
from datetime import datetime
now = datetime.now()
str_datetime = now.strptime("%Y-%m-%d %H:%M:%S")
print(str_datetime)
# output: 2022-11-02 23:52:11
convert "YYY-MM-DD HH:MM:SS" to datetime¶
- use
datetime.strftime
to convert string to datetime
from datetime import datetime
dt = datetime.strptime("2022-11-02 23:52:11", "%Y-%m-%d %H:%M:%S")
print(dt)
# output: 2022-11-02 23:52:11
Note: Read more about format codes [i.e
%Y
,%m
, etc] at Python official docs
difference between two datetime objects¶
from datetime import datetime
d1 = datetime(2022, 1, 3)
d2 = datetime(2022, 5, 3)
delta = d2 - d1
print(delta)
# output: 120 days, 0:00:00
print(type(delta))
# output: datetime.timedelta
- above program gives the timedelta between two datetime objects
time - module¶
- time module is python's built-in module, used to work with time
epoch - time¶
-
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).
-
Let's look at below code to get the epoch time
import time
epoch = time.time()
print(epoch)
# output: 1667615933.811202
convert epoch seconds to datetime string¶
- use
time.ctime(seconds)
to covert seconds to datetime string
import time
seconds = 1000
date_str = time.ctime(seconds)
print(date_str)
# output: 'Thu Jan 1 05:46:40 1970'
pause / delay a execution of a program¶
- use
time.sleep(seconds)
to delay execution. - let's see an example
import time
def wait_sec(sec):
time.sleep(sec)
print(f'I waited {sec} sec')
wait_sec(10)
# output: I waited 10 sec
- when we run the above program, it gives the output after 10 sec
measure program performance¶
- we can measure the run time of a program using time module.
- let's look at the code below.
from time import perf_counter, sleep
def wait_5sec():
sleep(5)
start = perf_counter()
wait_5sec()
end = perf_counter()
run_time = end - start
print(run_time)
# output: 5.005124709000029
- First, start captures the moment before you call the function. end captures the moment after the function returns. The function’s total execution time took (end - start) seconds.
To read more about time module visit python official docs