Time, Date, Timestamp in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(19 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
* https://docs.python.org/3/library/datetime.html
=Internal=
=Internal=
* [[Time#Time.2C_Date.2C_Timestamp_Handling_in_Python|Time]]
* [[Time#Time.2C_Date.2C_Timestamp_Handling_in_Python|Time]]
Line 4: Line 7:


=Overview=
=Overview=
Time, date and timestamps are handled with the <code>time</code> and <code>datetime</code> modules, available in the Standard Library.
The Standard Library <code>datetime</code> module provides <code>datetime</code>, <code>date</code> and <code>time</code> types. The <code>datetime</code> type combines information stored in <code>data</code> and <code>time</code> and it is the most commonly used. 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=
=<tt>datetime</tt> Module=
{{External|https://docs.python.org/3/library/datetime.html#module-datetime}}
{{External|https://docs.python.org/3/library/datetime.html#module-datetime}}
{{External|https://geekflare.com/calculate-time-difference-in-python/}}
{{External|https://geekflare.com/calculate-time-difference-in-python/}}
==<tt>datetime</tt> Overview==
==<tt>datetime</tt> Overview==
The <code>datetime</code> module provides classes for manipulating dates and times.
The <code>datetime</code> module provides classes for manipulating dates and times. The <code>datetime</code> package documentation seems to recommend the <code>[[#dateutil|dateutil]]</code> for time zone support and parsing.
https://docs.python.org/3/library/datetime.html#module-datetime


The <code>datetime</code> package documentation seems to recommend the <code>[[#dateutil|dateutil]]</code> for time zone support and parsing.
==<span id='datetime.datetime'></span>The <tt>datetime.datetime</tt> Type==
<code>datetime</code> is an immutable type, so methods that seem to modify an instance actually return new instances. Given a <code>datetime</code> instances, the equivalent <code>date</code> and <code>time</code> type instances can be obtained with <code>date()</code>, respectively <code>time()</code>.


==Time Interval with <tt>timedelta</tt>==
==Time Interval with <tt>timedelta</tt>==
The difference of two <code>datetime</code> objects produce a <code>datetime.timedelta</code> type:
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>
from datetime import datetime
from datetime import datetime
dt1 = datetime.datetime(2022,3,27,13,27,45,46000)  
dt1 = datetime(2022,3,27,13,10,45,46000)  
dt2 = datetime.datetime(2022,6,30,14,28)  
dt2 = datetime(2022,6,30,14,28)  
tdelta = dt2 - dt1  
tdelta = dt2 - dt1  
print(tdelta)  
print(tdelta)  
print(type(tdelta))  
print(type(tdelta))  
print(dt1.day) # prints 27
print(dt1.minute) # prints 10
</syntaxhighlight>
</syntaxhighlight>


Line 49: Line 47:
current_time = now.strftime("%H:%M:%S")
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Current Time =", current_time)
</syntaxhighlight>
==Current Date==
With <code>now()</code>:
<syntaxhighlight lang='py'>
from datetime import datetime
d = datetime.now().strftime("%Y-%m-%d")
print(d) # displays YYYY-mm-dd
</syntaxhighlight>


#
With <code>date.today()</code>:
# To display YYYY-mm-dd:
<syntaxhighlight lang='py'>
#
from datetime import date
print(f'{now.strftime("%Y-%m-%d")}')
print(str(date.today())) # displays YYYY-mm-dd
#
# equivalent
#
print(str(datetime.date.today()))
</syntaxhighlight>
</syntaxhighlight>


==Format==
==Format==


===Parsing from String===
<syntaxhighlight lang='py'>
<syntaxhighlight lang='py'>
from datetime import datetime
from datetime import datetime
Line 71: Line 77:
</syntaxhighlight>
</syntaxhighlight>


The common timestamp elements are '%Y-%m-%d %H:%M:%S'. <font color=darkkhaki>For more details on date format, see ?</font>
The common timestamp elements are '%Y-%m-%d %H:%M:%S'.  
 
ISO C89 compatible format specifications:
{| class="wikitable" style="text-align: left;"
! Type
! Description
|-
| %Y || Four-digit year
|-
| %y || Two-digit year
|-
| %m || Two-digit month [01, 12]
|-
| %d || Two-digit day [01, 31]
|-
| %H || Hour (24-hour clock) [00, 23]
|-
| %I || Hour (12-hour clock) [01, 12]
|-
| %M || Two-digit minute [00, 59]
|-
| %S || Second [00, 61] (seconds 60, 61 account for leap seconds)
|-
| %f || Microsecond as an integer, zero-padded (from 000000 to 999999)
|-
| %j || Day of the year as a zero-padded integer (from 001 to 336)
|-
| %w || Weekday as an integer [0 (Sunday), 6]
|-
| %u || Weekday as an integer starting from 1, where 1 is Monday.
|-
| %U || Week number of the year [00, 53]; Sunday is considered the first day of the week, and days before the first Sunday of the year are “week 0”
|-
| %W || Week number of the year [00, 53]; Monday is considered the first day of the week, and days before the first Monday of the year are “week 0”
|-
| %z || UTC time zone offset as +HHMM or -HHMM; empty if time zone naive
|-
| %Z || Time zone name as a string, or empty string if no time zone
|-
| %F  || Shortcut for %Y-%m-%d (e.g., 2012-4-18)
|-
| %D || Shortcut for %m/%d/%y (e.g., 04/18/12)
|-
|}
 
Also see [[#Time.2C_Date_and_Timestamp_Parsing_with_dateutil|Time, Date and Timestamp Parsing with <tt>dateutil</tt>]] below.
 
===Formating as String===
<syntaxhighlight lang='py'>
d = ...
d.strftime("%Y-%m-%d %H:%M")
</syntaxhighlight>
==Replace Time Fields==
<syntaxhighlight lang='py'>
dt_hour = dt.replace(minute=0, second=0)
</syntaxhighlight>
Since <code>datetime</code> is immutable, new instances will be generated.


=<SPAN ID='dateutil'></SPAN><tt>dateutil</tt> Module=
=<SPAN ID='dateutil'></SPAN><tt>dateutil</tt> Module=
{{External|https://pypi.org/project/python-dateutil/}}
{{External|https://pypi.org/project/python-dateutil/}}
==Time, Date and Timestamp Parsing==
==<span id='Time.2C_Date_and_Timestamp_Parsing'></span>Time, Date and Timestamp Parsing with <tt>dateutil</tt>==
The <code>[[#datetime|datetime]]</code> package documentation seems to recommend the <code>dateutil</code> for time zone support and parsing.
The <code>[[#datetime|datetime]]</code> package documentation seems to recommend the <code>dateutil</code> for time zone support and parsing.


Line 86: Line 148:
assert d.day == 1
assert d.day == 1
</syntaxhighlight>
</syntaxhighlight>
 
=<tt>time</tt> Module=
<font color=darkkhaki>
==Sleep==
TO PROCESS custom_date_parser = lambda x: datetime.strptime(x, "%Y-%d-%m %H:%M:%S")
<syntaxhighlight lang='py'>
</font>
from time import sleep
sleep(1)
</syntaxhighlight>

Latest revision as of 20:32, 16 May 2024

External

Internal

Overview

The Standard Library datetime module provides datetime, date and time types. The datetime type combines information stored in data and time and it is the most commonly used. Additionally, the dateutil module provides useful extensions.

datetime Module

https://docs.python.org/3/library/datetime.html#module-datetime
https://geekflare.com/calculate-time-difference-in-python/

datetime Overview

The datetime module provides classes for manipulating dates and times. The datetime package documentation seems to recommend the dateutil for time zone support and parsing.

The datetime.datetime Type

datetime is an immutable type, so methods that seem to modify an instance actually return new instances. Given a datetime instances, the equivalent date and time type instances can be obtained with date(), respectively time().

Time Interval with timedelta

The difference of two datetime objects produce a datetime.timedelta type:

from datetime import datetime
dt1 = datetime(2022,3,27,13,10,45,46000) 
dt2 = datetime(2022,6,30,14,28) 
tdelta = dt2 - dt1 
print(tdelta) 
print(type(tdelta)) 
print(dt1.day) # prints 27
print(dt1.minute) # prints 10

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)

Current Date

With now():

from datetime import datetime
d = datetime.now().strftime("%Y-%m-%d")
print(d) # displays YYYY-mm-dd

With date.today():

from datetime import date
print(str(date.today())) # displays YYYY-mm-dd

Format

Parsing from String

from datetime import datetime
s = '12/31/2023'
d = datetime.strptime(s, "%m/%d/%Y")
assert d.year == 2023
assert d.month == 12
assert d.day == 31

The common timestamp elements are '%Y-%m-%d %H:%M:%S'.

ISO C89 compatible format specifications:

Type Description
%Y Four-digit year
%y Two-digit year
%m Two-digit month [01, 12]
%d Two-digit day [01, 31]
%H Hour (24-hour clock) [00, 23]
%I Hour (12-hour clock) [01, 12]
%M Two-digit minute [00, 59]
%S Second [00, 61] (seconds 60, 61 account for leap seconds)
%f Microsecond as an integer, zero-padded (from 000000 to 999999)
%j Day of the year as a zero-padded integer (from 001 to 336)
%w Weekday as an integer [0 (Sunday), 6]
%u Weekday as an integer starting from 1, where 1 is Monday.
%U Week number of the year [00, 53]; Sunday is considered the first day of the week, and days before the first Sunday of the year are “week 0”
%W Week number of the year [00, 53]; Monday is considered the first day of the week, and days before the first Monday of the year are “week 0”
%z UTC time zone offset as +HHMM or -HHMM; empty if time zone naive
%Z Time zone name as a string, or empty string if no time zone
%F Shortcut for %Y-%m-%d (e.g., 2012-4-18)
%D Shortcut for %m/%d/%y (e.g., 04/18/12)

Also see Time, Date and Timestamp Parsing with dateutil below.

Formating as String

d = ...
d.strftime("%Y-%m-%d %H:%M")

Replace Time Fields

dt_hour = dt.replace(minute=0, second=0)

Since datetime is immutable, new instances will be generated.

dateutil Module

https://pypi.org/project/python-dateutil/

Time, Date and Timestamp Parsing with dateutil

The datetime package documentation seems to recommend the dateutil for time zone support and parsing.

import dateutil.parser as du

d = du.parse('10/01/2023')
assert d.year == 2023
assert d.month == 10
assert d.day == 1

time Module

Sleep

from time import sleep
sleep(1)