Time, Date, Timestamp in Python: Difference between revisions
Jump to navigation
Jump to search
Line 7: | Line 7: | ||
Additionally, the <code>dateutil</code> module provides useful extensions. | Additionally, the <code>dateutil</code> module provides useful extensions. | ||
=<tt>time</tt> Module= | |||
==Sleep== | |||
<syntaxhighlight lang='py'> | |||
from time import sleep | |||
sleep(1) | |||
</syntaxhighlight> | |||
=<tt>datetime</tt> Module= | |||
{{External|https://geekflare.com/calculate-time-difference-in-python/}} | |||
==Time Interval with <tt>timedelta</tt>== | |||
<syntaxhighlight lang='py'> | |||
from datetime import datetime | |||
dt1 = datetime.datetime(2022,3,27,13,27,45,46000) | |||
dt2 = datetime.datetime(2022,6,30,14,28) | |||
tdelta = dt2 - dt1 | |||
print(tdelta) | |||
print(type(tdelta)) | |||
</syntaxhighlight> | |||
To get the total number of seconds in <code>timedelta</code>, use <code>total_seconds()</code>: | |||
<syntaxhighlight lang='py'> | |||
from datetime import datetime | |||
t0 = datetime.now() | |||
... | |||
t1 = datetime.now() | |||
print((t1 - t0).total_seconds()) | |||
</syntaxhighlight> | |||
==now Time== | |||
<syntaxhighlight lang='py'> | |||
from datetime import datetime | |||
now = datetime.now() | |||
current_time = now.strftime("%H:%M:%S") | |||
print("Current Time =", current_time) | |||
# | |||
# To display YYYY-mm-dd: | |||
# | |||
print(f'{now.strftime("%Y-%m-%d")}') | |||
# | |||
# equivalent | |||
# | |||
print(str(datetime.date.today())) | |||
</syntaxhighlight> |
Revision as of 21:37, 8 October 2023
Internal
Overview
Time, date and timestamps are handled with the time
and datetime
modules, available in the Standard Library.
Additionally, the dateutil
module provides useful extensions.
time Module
Sleep
from time import sleep
sleep(1)
datetime Module
Time Interval with timedelta
from datetime import datetime
dt1 = datetime.datetime(2022,3,27,13,27,45,46000)
dt2 = datetime.datetime(2022,6,30,14,28)
tdelta = dt2 - dt1
print(tdelta)
print(type(tdelta))
To get the total number of seconds in timedelta
, use total_seconds()
:
from datetime import datetime
t0 = datetime.now()
...
t1 = datetime.now()
print((t1 - t0).total_seconds())
now Time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
#
# To display YYYY-mm-dd:
#
print(f'{now.strftime("%Y-%m-%d")}')
#
# equivalent
#
print(str(datetime.date.today()))