Differences between revisions 2 and 12 (spanning 10 versions)
Revision 2 as of 2023-04-12 01:50:45
Size: 4888
Comment:
Revision 12 as of 2023-04-12 15:17:54
Size: 8346
Comment:
Deletions are marked like this. Additions are marked like this.
Line 13: Line 13:
A datetime.date object is constructed as:

{{{
d1 = datetime.datetime(2020, 12, 31, 23, 59, 59, 999999, tzinfo=None)
A `datetime.datetime` object is constructed as:

{{{
dt1 = datetime.datetime(2020, 12, 31, 23, 59, 59, 999999, tzinfo=None)
Line 22: Line 22:
dt1 = datetime.datetime(2020, 12, 31) dt2 = datetime.datetime(2020, 12, 31)
Line 86: Line 86:
 3. Time zone offsets are allowed to have fractional seconds  3. Timezone offsets are allowed to have fractional seconds
Line 106: Line 106:
To set the time zone, pass the optional `tzinfo` argument. To set the timezone, pass the optional `tzinfo` argument.
Line 120: Line 120:
To set the time zone, pass the optional `tzinfo` argument. To set the timezone, pass the optional `tzinfo` argument.
Line 150: Line 150:
Construct a `datetime.datetime` from a string representing a POSIX timestamp. The time zone is set to `None`. Construct a `datetime.datetime` from a string representing a POSIX timestamp. The timezone is set to `None`.
Line 160: Line 160:
A naive (i.e. time zone is stripped out) `datetime.datetime` representing the current date and time in UTC.

`datetime.datetime.now` is preferred because naive `datetime.datetime` objects are assumed to be local, and this function defies that logic.
A timezone naive `datetime.datetime` representing the current date and time in UTC.

`datetime.datetime.now` is preferred because naive `datetime.datetime` objects are assumed to be local, and this function defies that logic. Instead consider using:

{{{
import datetime

datetime.datetime(2023, 4, 12, 13, 59, 53, 654456, tzinfo=datetime.timezone.utc)
}}}
Line 174: Line 180:
Return a copy of the `datetime.datetime` object with the timezone replaced and any appropriate offsets applied. If a timezone is not passed as an argument, the local timezone is used.

{{{
import datetime

dt1 = datetime.datetime.now(datetime.timezone.utc)
dt2 = dt1.astimezone(datetime.timezone(datetime.timedelta(hours=-5)))
}}}

----
Line 178: Line 195:
Return a string like `Wed Dec 4 20:30:40 2002`.

Equivalent to `time.ctime(time.mktime(dt1.timetuple()))`.

----
Line 182: Line 205:
Return a `datetime.date` object containing the time components (`year`, `month`, `day`).

----
Line 186: Line 213:
A passthrough to `datetime.timezone.dst` for the `tzinfo` component of `datetime.datetime`.

If `tzinfo` is None, returns None.

----
Line 190: Line 223:
Return a named tuple like `datetime.IsoCalendarDate(year, week, weekday)`.

----
Line 194: Line 231:
Return a string like `YYYY-MM-DDTHH:MM:SS`. Appends microseconds like `.ffffff` if not 0. Appends timezone offset like `+HH:MM[:SS[.ffffff]]` if not timezone naive.

----
Line 198: Line 239:
Return the weekday as an integer between 1 (Monday) and 7 (Sunday).

----
Line 202: Line 247:
Return a copy of the `datetime.datetime` object with the specified components replaced.

{{{
import datetime

dt1 = datetime.datetime(2020, 12, 25, 23, 59, 59, 999999, tzinfo=datetime.timezone.utc)
dt2 = dt1.replace(tzinfo=None)
dt3 = dt2.replace(year=2021)
dt4 = dt3.replace(hour=0)
}}}

----
Line 206: Line 264:
Return a formatted string timestamp.

See [[Python/Datetime#StrFTime_and_StrPTime|here]] for an explanation of the directives.

----
Line 210: Line 274:
Return a `datetime.time` object containing the time components (`hour`, `minute`, `second`, `millisecond`, and `fold`). Compare to `datetime.datetime.timetz`.

----
Line 214: Line 282:
Return a float representing a POSIX timestamp.

May raise an `OverflowError` depending on the local `libc` (specifically the `mktime()` implementation).

----
Line 218: Line 292:
Return a time tuple like `time.localtime()`.

Equivalent to `time.struct_time((dt1.year, dt1.month, dt1.day, dt1.hour, dt1.minute, dt1.second, dt1.weekday(), dt1.toordinal() - datetime.date(dt1.year, 1, 1).toordinal() + 1, -1))`.

Note the last argument would actually be `1` if `datetime.datetime.dst` returned any non-zero code, or `0` if it returned `0` specifically.

----
Line 222: Line 304:
Return a `datetime.time` object containing the time components ''and'' the `tzinfo`.

----
Line 226: Line 312:
Return the proleptic Gregorian ordinal.

----
Line 230: Line 320:
A passthrough to `datetime.timezone.tzname` for the `tzinfo` component of `datetime.datetime`.

If the `datetime.datetime` object is timezone naive, returns None.

----
Line 234: Line 330:
A passthrough to `datetime.timezone.utcoffset` for the `tzinfo` component of `datetime.datetime`.

If the `datetime.datetime` object is timezone naive, returns None.

----
Line 238: Line 340:
Same as `datetime.datetime.timetuple` except that the last argument is forced to `0`.

If the `datetime.datetime` object is not timezone naive, the time is adjusted for UTC before generating the tuple.

----
Line 242: Line 350:
Return the weekday as an integer between 0 (Monday) and 6 (Sunday).
Line 250: Line 360:
||'''Operation''' ||'''Meaning''' ||
||`dt1 + timedelta` ||returns a new datetime representing `dt1` incremented by the duration||
||`dt1 - timedelta` ||returns a new datetime representing `dt1` decremented by the duration||
||`dt1 - dt2` ||returns a `datetime.timedelta` ||
||`dt1 < dt2` ||returns `True` if `dt1` is earlier than `dt2` else `False` ||

Two `datetime.datetime` objects can only be used in operations together if both have timezone information, or both are naive to timezones. Mixing categories will raise a `TypeError`.
||'''Operation''' ||'''Meaning'''                        ||
||`dt1 + timedelta` ||returns a new datetime representing `dt1` incremented by the duration                       ||
||`dt1 - timedelta` ||returns a new datetime representing `dt1` decremented by the duration                       ||
||`dt1 - dt2` ||returns a `datetime.timedelta`                        ||
||`dt1 < dt2` ||returns `True` if `dt1` is earlier than `dt2` else `False`                        ||
||`dt1 == dt2` ||returns `True` if `dt1` represents the same UTC or timezone naive time as `dt2` else `False`
||

Two `datetime.datetime` objects can only be used in operations together if both have timezone information, or both are naive to timezones. Mixing categories will raise a `TypeError`, except for the `==` and `!=` operators (which will always indicate that the two are unlike)..

Python Datetime Datetime

A datetime.datetime object represents a date and time.


Usage

A datetime.datetime object is constructed as:

dt1 = datetime.datetime(2020, 12, 31, 23, 59, 59, 999999, tzinfo=None)

While the year, month, and date are required, the remaining options are optional.

dt2 = datetime.datetime(2020, 12, 31)

The components can be accessed like:

dt1.year         # 2020
dt1.month        # 12
dt1.day          # 25
dt1.hour         # 23
dt1.minute       # 59
dt1.second       # 59
dt1.millisecond  # 999999
dt1.tzinfo       # None
dt1.fold         # 0

Note that fold is used to indicate a time that is 'repeated' (as in 'setting the clock back').


Class Functions

Combine

Construct a datetime.datetime from a datetime.date and a datetime.time.

dt1 = datetime.datetime.combine(d1, t1)

To override the tzinfo from the datetime.time object, pass the optional tzinfo argument.


FromIsoCalendar

Construct a datetime.datetime from the year, week, and weekday.


FromIsoFormat

To construct a datetime.datetime from most valid ISO 8601 strings, try:

import datetime

datetime.datetime.fromisoformat('2019-12-04')            #datetime.datetime(2019, 12, 4, 0, 0)
datetime.datetime.fromisoformat('20191204')              #datetime.datetime(2019, 12, 4, 0, 0)
datetime.datetime.fromisoformat('2011-11-04T00:05:23')   #datetime.datetime(2011, 11, 4, 0, 5, 23)
datetime.datetime.fromisoformat('2011-11-04T00:05:23Z')  #datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)
  1. Ordinal dates are not supported by this function
  2. The T separator is allowed to be any character

  3. Timezone offsets are allowed to have fractional seconds
  4. Hours and minutes are not allowed to be fractional


FromOrdinal

Construct a datetime.datetime from a proleptic Gregorian ordinal.


FromTimestamp

Construct a datetime.datetime from a string representing a POSIX timestamp.

May raise an OverflowError or OSError depending on the local libc (specifically the localtime() implementation).

To set the timezone, pass the optional tzinfo argument.


Now

A datetime.datetime representing the current date and time can be constructed like:

dt1 = datetime.datetime.now()

To set the timezone, pass the optional tzinfo argument.


StrPTime

Construct a datetime.datetime from a formatted string timestamp.

See here for an explanation of the directives.


Today

A datetime.datetime representing the current date and time (and no timezone information) can be constructed like:

dt1 = datetime.datetime.today()


UtcFromTimeStamp

Construct a datetime.datetime from a string representing a POSIX timestamp. The timezone is set to None.

May raise an OverflowError or OSError depending on the local libc (specifically the localtime() implementation).


UtcNow

A timezone naive datetime.datetime representing the current date and time in UTC.

datetime.datetime.now is preferred because naive datetime.datetime objects are assumed to be local, and this function defies that logic. Instead consider using:

import datetime

datetime.datetime(2023, 4, 12, 13, 59, 53, 654456, tzinfo=datetime.timezone.utc)


Methods

AsTimeZone

Return a copy of the datetime.datetime object with the timezone replaced and any appropriate offsets applied. If a timezone is not passed as an argument, the local timezone is used.

import datetime

dt1 = datetime.datetime.now(datetime.timezone.utc)
dt2 = dt1.astimezone(datetime.timezone(datetime.timedelta(hours=-5)))


CTime

Return a string like Wed Dec  4 20:30:40 2002.

Equivalent to time.ctime(time.mktime(dt1.timetuple())).


Date

Return a datetime.date object containing the time components (year, month, day).


Dst

A passthrough to datetime.timezone.dst for the tzinfo component of datetime.datetime.

If tzinfo is None, returns None.


IsoCalendar

Return a named tuple like datetime.IsoCalendarDate(year, week, weekday).


IsoFormat

Return a string like YYYY-MM-DDTHH:MM:SS. Appends microseconds like .ffffff if not 0. Appends timezone offset like +HH:MM[:SS[.ffffff]] if not timezone naive.


IsoWeekDay

Return the weekday as an integer between 1 (Monday) and 7 (Sunday).


Replace

Return a copy of the datetime.datetime object with the specified components replaced.

import datetime

dt1 = datetime.datetime(2020, 12, 25, 23, 59, 59, 999999, tzinfo=datetime.timezone.utc)
dt2 = dt1.replace(tzinfo=None)
dt3 = dt2.replace(year=2021)
dt4 = dt3.replace(hour=0)


StrFTime

Return a formatted string timestamp.

See here for an explanation of the directives.


Time

Return a datetime.time object containing the time components (hour, minute, second, millisecond, and fold). Compare to datetime.datetime.timetz.


TimeStamp

Return a float representing a POSIX timestamp.

May raise an OverflowError depending on the local libc (specifically the mktime() implementation).


TimeTuple

Return a time tuple like time.localtime().

Equivalent to time.struct_time((dt1.year, dt1.month, dt1.day, dt1.hour, dt1.minute, dt1.second, dt1.weekday(), dt1.toordinal() - datetime.date(dt1.year, 1, 1).toordinal() + 1, -1)).

Note the last argument would actually be 1 if datetime.datetime.dst returned any non-zero code, or 0 if it returned 0 specifically.


TimeTz

Return a datetime.time object containing the time components and the tzinfo.


ToOrdinal

Return the proleptic Gregorian ordinal.


TzName

A passthrough to datetime.timezone.tzname for the tzinfo component of datetime.datetime.

If the datetime.datetime object is timezone naive, returns None.


UtcOffset

A passthrough to datetime.timezone.utcoffset for the tzinfo component of datetime.datetime.

If the datetime.datetime object is timezone naive, returns None.


UtcTimeTuple

Same as datetime.datetime.timetuple except that the last argument is forced to 0.

If the datetime.datetime object is not timezone naive, the time is adjusted for UTC before generating the tuple.


WeekDay

Return the weekday as an integer between 0 (Monday) and 6 (Sunday).


Operations

datetime.datetime objects can be used with the following operators and functions.

Operation

Meaning

dt1 + timedelta

returns a new datetime representing dt1 incremented by the duration

dt1 - timedelta

returns a new datetime representing dt1 decremented by the duration

dt1 - dt2

returns a datetime.timedelta

dt1 < dt2

returns True if dt1 is earlier than dt2 else False

dt1 == dt2

returns True if dt1 represents the same UTC or timezone naive time as dt2 else False

Two datetime.datetime objects can only be used in operations together if both have timezone information, or both are naive to timezones. Mixing categories will raise a TypeError, except for the == and != operators (which will always indicate that the two are unlike)..


CategoryRicottone

Python/Datetime/Datetime (last edited 2023-04-12 15:17:54 by DominicRicottone)