23
loading...
This website collects cookies to deliver better user experience
This is Day 18 of the #100DaysOfPython challenge.
time
module from Python's standard library to explore how we can work with different time capabilities such as getting the local time and sleeping within a program.hello-python-time-module
directory and install Pillow.# Make the `hello-python-time-module` directory
$ mkdir hello-python-time-module
$ cd hello-python-time-module
# Init the virtual environment
$ pipenv --three
$ pipenv install --dev ipython
time
module using iPython
.pipenv run ipython
from the command line to open up the REPL.time
module. We can do so from within the REPL with the following:import time
time
module by checking the __name__
attribute and playing around with a few methods.time.__name__ # 'time'
time.time() # 1628200068.664737
time
that we called on the module returns the time in seconds since the epoch as a floating point number.time.localtime() # time.struct_time(tm_year=2021, tm_mon=8, tm_mday=6, tm_hour=7, tm_min=46, tm_sec=20, tm_wday=4, tm_yday=218, tm_isdst=0)
time.gmtime() # time.struct_time(tm_year=2021, tm_mon=8, tm_mday=5, tm_hour=21, tm_min=46, tm_sec=32, tm_wday=3, tm_yday=217, tm_isdst=0)
time.asctime(time.localtime()) # 'Fri Aug 6 07:51:53 2021'
time.strptime("30 Nov 00", "%d %b %y") # time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
time.strftime("%m/%d/%Y, %H:%M:%S") # '08/06/2021, 07:56:44'
time.strftime("%d %b %y", time.strptime("30 Nov 00", "%d %b %y")) # '30 Nov 00'
time.sleep(5) # notice that the REPL does not return until 5 seconds have passed
datetime.datetime.fromtimestamp
method.import datetime
# Check time now is less than 1 second later
datetime.datetime.fromtimestamp(time.time()) < datetime.datetime.now() + datetime.timedelta(seconds=1) # True
# Check time now is after 1 second before
datetime.datetime.fromtimestamp(time.time()) < datetime.datetime.now() - datetime.timedelta(seconds=1) # False
datetime
comparisons, see my post on Datetime In Python and more from my series Working with dates and times in Python.time
module from Python's standard library.datetime
module.pawel_czerwinski