python datetime module

Introduction

datetime Basic date and time types

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. For related functionality, see also the time and calendar modules.

datetime include constants and available types

1
2
3
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

The datetime module constants

datetime.MINYEAR

The smallest year number allowed in a date or datetime object. MINYEAR is 1.

datatime.MAXYEAR

The largest year number allowed in a date or datetime object. MAXYEAR is 9999.

The datetime module available types

class datetime.timedelta

A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.

class datetime.date

An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day.

class datetime.time

An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds (there is no notion of “leap seconds” here). Attributes: hour, minute, second, microsecond, and tzinfo.

class datetime.datetime

A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.

class datetime.tzinfo

An abstract base class for time zone information objects. These are used by the datetime and time classes to provide a customizable notion of time adjustment (for example, to account for time zone and/or daylight saving time).

class datetime.timezone

A class that implements the tzinfo abstract base class as a fixed offset from the UTC.

timedelta Objects

A timedelta object represents a duration, the difference between two dates or times.

1
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.

Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

  • A millisecond is converted to 1000 microseconds.

  • A minute is converted to 60 seconds.

  • An hour is converted to 3600 seconds.

  • A week is converted to 7 days.

days, seconds and microseconds are then normalized so that the representation is unique, with

  • 0 <= microseconds < 1000000
  • 0 <= seconds < 3600*24 (the number of seconds in one day)
  • -999999999 <= days <= 999999999
1
2
3
4
>>> from datetime import timedelta		     
>>> dir(timedelta)

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']

Class attributes

timedelta.min

The most negative timedelta object, timedelta(-999999999).

1
2
>>> timedelta.min		     
datetime.timedelta(days=-999999999)

timedelta.max

The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).

1
2
>>> timedelta.max			     
datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)

timedelta.resolution

The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1).

1
2
>>> timedelta.resolution	     
datetime.timedelta(microseconds=1)

Instance attributes (read-only)

timedelta.days

timedelta.seconds

timedelta.microseconds

Attribute Value
days Between -999999999 and 999999999 inclusive
seconds Between 0 and 86399 inclusive
microseconds Between 0 and 999999 inclusive
1
2
3
4
>>> from datetime import timedelta
>>> d = timedelta(days=1,seconds=1,microseconds=1)
>>> (d.days, d.seconds, d.microseconds)
(1, 1, 1)

Instance methods

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to td / timedelta(seconds=1). For interval units other than seconds, use the division form directly (e.g. td / timedelta(microseconds=1)).

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

Example usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=600)
>>> year.total_seconds()
31536000.0
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years
datetime.timedelta(3650)
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True

Supported operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> from datetime import timedelta
>>> t1 = timedelta(days=1,seconds=1,microseconds=1)
>>> t2 = timedelta(days=2,seconds=2,microseconds=2)

>>> t1 + t2
datetime.timedelta(days=3, seconds=3, microseconds=3)

>>> t2 - t1
datetime.timedelta(days=1, seconds=1, microseconds=1)
>>> t1 - t2
datetime.timedelta(days=-2, seconds=86398, microseconds=999999)

>>> 6 * t1
datetime.timedelta(days=6, seconds=6, microseconds=6)
>>> 6.6 * t1
datetime.timedelta(days=6, seconds=51846, microseconds=600007)

>>> abs(t1)
datetime.timedelta(days=1, seconds=1, microseconds=1)
>>> abs(t1 - t2)
datetime.timedelta(days=1, seconds=1, microseconds=1)
# equivalent to +t when t.days >= 0, and to -t when t.days < 0. (2)

>>> str(t1)
'1 day, 0:00:01.000001'
# Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> repr(t1)
'datetime.timedelta(days=1, seconds=1, microseconds=1)'
# Returns a string representation of the timedelta object as a constructor call with canonical attribute values.

In addition to the operations listed above timedelta objects support certain additions and subtractions with date and datetime objects .

date Objects

A date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions. January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on.

1
class datetime.date(year, month, day)

All arguments are required. Arguments may be integers, in the following ranges:

  • MINYEAR <= year <= MAXYEAR

  • 1 <= month <= 12

  • 1 <= day <= number of days in the given month and year

If an argument outside those ranges is given, ValueError is raised.

1
2
3
4
>>> from datetime import date
>>> dir(date)

['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']

Class attributes

date.min

The earliest representable date, date(MINYEAR, 1, 1).

1
2
3
4
>>> from datetime import date

>>> date.min
datetime.date(1, 1, 1)

date.max

The latest representable date, date(MAXYEAR, 12, 31).

1
2
3
4
>>> from datetime import date

>>> date.max
datetime.date(9999, 12, 31)

date.resolution

The smallest possible difference between non-equal date objects, timedelta(days=1).

1
2
3
4
>>> from datetime import date

>>> date.resolution
datetime.timedelta(days=1)

Instance attributes (read-only)

date.year

Between MINYEAR and MAXYEAR inclusive.

date.month

Between 1 and 12 inclusive.

date.day

Between 1 and the number of days in the given month of the given year.

Class methods

date.today()

Return the current local date. This is equivalent to date.fromtimestamp(time.time()).

1
2
3
>>> from datetime import date
>>> date.today()
datetime.date(2019, 8, 3)

date.fromtimestamp(timestamp)

Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().

1
2
3
4
5
>>> import time
>>> from datetime import date

>>> date.fromtimestamp(time.time())
datetime.date(2019, 8, 3)

date.fromordinal(ordinal)

Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, date.fromordinal(d.toordinal()) == d.

1
2
3
4
5
6
7
8
9
10
>>> from datetime import date

>>> date.fromordinal(1)
datetime.date(1, 1, 1)

>>> date.fromordinal(31)
datetime.date(1, 1, 31)

>>> date.fromordinal(35)
datetime.date(1, 2, 4)

date.fromisoformat(date_string)

Return a date corresponding to a date_string in the format emitted by date.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD.

Caution This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of date.isoformat().

1
2
3
4
5
>>> from datetime import date

>>> d = "2018-10-10"
>>> date.fromisoformat(d)
datetime.date(2018, 10, 10)

Instance methods

date.replace(year=self.year, month=self.month, day=self.day)

Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified.

For example

1
2
3
4
5
6
7
8
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.replace(month=12)
datetime.date(2018, 12, 10)

>>> d.replace(month=12) == date(2018, 12, 10)
True

date.timetuple()

Return a time.struct_time such as returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple() is equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)), where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.timetuple()
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=283, tm_isdst=-1)

date.toordinal()

Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. For any date object d, date.fromordinal(d.toordinal()) == d.

1
2
3
4
5
6
7
8
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.toordinal()
736977

>>> date.fromordinal(d.toordinal()) == d
True

date.weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

For example,date(2018, 10, 10).weekday() == 2, a Wednesday.

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.weekday()
2 # is Wednesday

date.isoweekday()

Return the day of the week as an integer, where Monday is 1 and Sunday is 7.

For example,date(2018, 10, 10).isoweekday() == 3, a Wednesday

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.isoweekday()
3 # is Wednesday

date.isocalendar()

Return a 3-tuple, (ISO year, ISO week number, ISO weekday).

The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

For example, 2004 begins on a Thursday, so the first week of ISO year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that date(2003, 12, 29).isocalendar() == (2004, 1, 1) and date(2004, 1, 4).isocalendar() == (2004, 1, 7).

1
2
3
4
5
>>> from datetime import date

>>> d = date(2004, 1, 1)
>>> d.isocalendar()
(2004, 1, 4)

date.isoformat()

Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.

For example

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.isoformat()
'2018-10-10'

date.__str__()

For a date d, str(d) is equivalent to d.isoformat().

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> str(d)
'2018-10-10'

date.ctime()

Return a string representing the date, is equivalent to time.ctime(time.mktime(d.timetuple())) on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

1
2
3
4
5
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.ctime()
'Wed Oct 10 00:00:00 2018'

date.strftime(format)

Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values

1
2
3
4
5
6
7
>>> from datetime import date

>>> d = date(2018, 10, 10)
>>> d.strftime('%Y-%m-%d')
'2018-10-10'
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2018-10-10 00:00:00'

date.__format__(format)

Same as date.strftime(). This makes it possible to specify a format string for a date object in formatted string literals and when using str.format().

Supported operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> from datetime import date
>>> from datetime import timedelta

>>> d1 = date(2018, 10, 10)
>>> d2 = date(2019, 11, 11)
>>> day = timedelta(days=15)

>>> d2 - d1
datetime.timedelta(days=397)

>>> d1 - d2
datetime.timedelta(days=-397)

>>> d1 < d2
True

>>> d1 + day
datetime.date(2018, 10, 25)
>>> d2 - day
datetime.date(2019, 10, 27)

time Objects

A time object represents a (local) time of day, independent of any particular day, and subject to adjustment via a tzinfo object.

1
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be integers, in the following ranges:

  • 0 <= hour < 24,

  • 0 <= minute < 60,

  • 0 <= second < 60,

  • 0 <= microsecond < 1000000,

  • fold in [0, 1].

If an argument outside those ranges is given,ValueError is raised. All default to 0 except tzinfo, which defaults to None.

1
2
3
4
>>> from datetime import time

>>> dir(time)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dst', 'fold', 'fromisoformat', 'hour', 'isoformat', 'max', 'microsecond', 'min', 'minute', 'replace', 'resolution', 'second', 'strftime', 'tzinfo', 'tzname', 'utcoffset']

Class attributes

time.min

The earliest representable time, time(0, 0, 0, 0).

1
2
3
4
>>> from datetime import time

>>> time.min
datetime.time(0, 0)

time.max

The latest representable time, time(23, 59, 59, 999999).

1
2
3
4
>>> from datetime import time

>>> time.max
datetime.time(23, 59, 59, 999999)

time.resolution

The smallest possible difference between non-equal time objects, timedelta(microseconds=1), although note that arithmetic on time objects is not supported.

1
2
3
4
>>> from datetime import time

>>> time.resolution
datetime.timedelta(microseconds=1)

Instance attributes

time.hour

In range(24).

time.minute

In range(60).

time.second

In range(60).

time.microsecond

In range(1000000).

time.tzinfo

The object passed as the tzinfo argument to the time constructor, or None if none was passed.

time.fole

In [0, 1]. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The value 0 (1) represents the earlier (later) of the two moments with the same wall time representation.

1
2
3
4
5
>>> from datetime import time

>>> t = time(10, 23, 56)
>>> t.hour, t.minute, t.second, t.microsecond, t.tzinfo, t.fold
(10, 23, 56, 0, None, 0)

Class methods

time.fromisoformat(time_sting)

Return a time corresponding to a time_string in one of the formats emitted by time.isoformat(). Specifically, this function supports strings in the format(s) HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]].

Instance methods

time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)

Return a time with the same value, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive time from an aware time, without conversion of the time data.

New in version 3.6: Added the fold argument.

time.isoformat(timespec=’auto’)

Return a string representing the time in ISO 8601 format, HH:MM:SS.ffffff or, if microsecond is 0, HH:MM:SS If utcoffset() does not return None, a string is appended, giving the UTC offset: HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] or, if self.microsecond is 0, HH:MM:SS+HH:MM[:SS[.ffffff]].

The optional argument timespec specifies the number of additional components of the time to include (the default is ‘auto’). It can be one of the following:

  • ‘auto’: Same as ‘seconds’ if microsecond is 0, same as ‘microseconds’ otherwise.

  • ‘hours’: Include the hour in the two-digit HH format.

  • ‘minutes’: Include hour and minute in HH:MM format.

  • ‘seconds’: Include hour, minute, and second in HH:MM:SS format.

  • ‘milliseconds’: Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format.

  • ‘microseconds’: Include full time in HH:MM:SS.ffffff format.

ValueError will be raised on an invalid timespec argument.

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> from datetime import time

>>> t = time(hour=12, minute=34, second=56, microsecond=123456)
>>> t.isoformat()
'12:34:56.123456'
>>> t.isoformat(timespec='minutes')
'12:34'

>>> t = time(hour=12, minute=34, second=56, microsecond=0)
>>> t.isoformat(timespec='microseconds')
'12:34:56.000000'
>>> t.isoformat(timespec='auto')
'12:34:56'

time.str()

For a time t, str(t) is equivalent to t.isoformat().

time.strftime(format)

Return a string representing the time, controlled by an explicit format string.

1
2
3
4
5
>>> from datetime import time

>>> t = time(hour=12, minute=34, second=56, microsecond=0)
>>> t.strftime('%H:%M:%S')
'12:34:56'

time.__format__(format)

Same as time.strftime(). This makes it possible to specify a format string for a time object in formatted string literals and when using str.format().

time.utcoffset()

If tzinfo is None, returns None, else returns self.tzinfo.utcoffset(None), and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.

Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes.

time.dst()

If tzinfo is None, returns None, else returns self.tzinfo.dst(None), and raises an exception if the latter doesn’t return None, or a timedelta object with magnitude less than one day.

Changed in version 3.7: The DST offset is not restricted to a whole number of minutes.

time.tzname()

If tzinfo is None, returns None, else returns self.tzinfo.tzname(None), or raises an exception if the latter doesn’t return None or a string object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> from datetime import time, tzinfo, timedelta
>>> class TZ1(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=1)
... def dst(self, dt):
... return timedelta(0)
... def tzname(self,dt):
... return "+01:00"
... def __repr__(self):
... return f"{self.__class__.__name__}()"
...
>>> t = time(12, 10, 30, tzinfo=TZ1())
>>> t
datetime.time(12, 10, 30, tzinfo=TZ1())
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'+01:00'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
>>> 'The {} is {:%H:%M}.'.format("time", t)
'The time is 12:10.'

datetime Objects

A datetime object is a single object containing all the information from a date object and a time object. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day.

1
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be integers, in the following ranges:

  • MINYEAR <= year <= MAXYEAR,

  • 1 <= month <= 12,

  • 1 <= day <= number of days in the given month and year,

  • 0 <= hour < 24,

  • 0 <= minute < 60,

  • 0 <= second < 60,

  • 0 <= microsecond < 1000000,

  • fold in [0, 1].

If an argument outside those ranges is given, ValueError is raised.

New in version 3.6: Added the fold argument.

1
2
3
4
>>> from datetime import datetime

>>> dir(datetime)
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromisoformat', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']

Class attributes

datetime.min

The earliest representable datetime, datetime(MINYEAR, 1, 1, tzinfo=None).

datetime.max

The latest representable datetime, datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None).

datetime.resolution

The smallest possible difference between non-equal datetime objects, timedelta(microseconds=1).

Instance attributes (read-only)

datetime.year

Between MINYEAR and MAXYEAR inclusive.

datetime.month

Between 1 and 12 inclusive.

datetime.day

Between 1 and the number of days in the given month of the given year.

datetime.hour

In range(24).

datetime.minute

In range(60).

datetime.second

In range(60).

datetime.microsecond

In range(1000000).

datetime.tzinfo

The object passed as the tzinfo argument to the datetime constructor, or None if none was passed.

datetime.fold

In [0, 1]. Used to disambiguate wall times during a repeated interval. (A repeated interval occurs when clocks are rolled back at the end of daylight saving time or when the UTC offset for the current zone is decreased for political reasons.) The value 0 (1) represents the earlier (later) of the two moments with the same wall time representation.

Class methods

datetime.today()

Return the current local datetime, with tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()).

1
2
3
>>> from datetime import datetime
>>> datetime.today()
datetime.datetime(2019, 8, 3, 23, 38, 14, 444364)

datetime.now(tz=None)

Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).

If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)).

datetime.utcnow()

Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc). See also now().

datetime.fromtimestamp(timestamp, tz=None)

Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

If tz is not None, it must be an instance of a tzinfo subclass, and the timestamp is converted to tz’s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).

datetime.utcfromtimestamp(timestamp)

Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. This may raise OverflowError, if the timestamp is out of the range of values supported by the platform C gmtime() function, and OSError on gmtime() failure. It’s common for this to be restricted to years in 1970 through 2038.

datetime.fromordinal(ordinal)

Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= datetime.max.toordinal(). The hour, minute, second and microsecond of the result are all 0, and tzinfo is None.

datetime.combine(date, time, tzinfo=self.tzinfo)

Return a new datetime object whose date components are equal to the given date object’s, and whose time components are equal to the given time object’s. If the tzinfo argument is provided, its value is used to set the tzinfo attribute of the result, otherwise the tzinfo attribute of the time argument is used.

For any datetime object d, d == datetime.combine(d.date(), d.time(), d.tzinfo). If date is a datetime object, its time components and tzinfo attributes are ignored.

Changed in version 3.6: Added the tzinfo argument.

datetime.fromisoformat(date_string)

Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * can match any single character.

datetime.strptime(date_string, format)

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])). ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.

Instance methods

datetime.date()

Return date object with same year, month and day.

datetime.time()

Return time object with same hour, minute, second, microsecond and fold. tzinfo is None. See also method timetz().

Changed in version 3.6: The fold value is copied to the returned time object.

datetime.timetz()

Return time object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method time().

Changed in version 3.6: The fold value is copied to the returned time object.

datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.

New in version 3.6: Added the fold argument.

datetime.astimezone(tz=None)

Return a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time.

If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. If self is naive, it is presumed to represent time in the system timezone.

datetime.utcoffset()

If tzinfo is None, returns None, else returns self.tzinfo.utcoffset(self), and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.

Changed in version 3.7: The UTC offset is not restricted to a whole number of minutes.

datetime.dst()

If tzinfo is None, returns None, else returns self.tzinfo.dst(self), and raises an exception if the latter doesn’t return None or a timedelta object with magnitude less than one day.

Changed in version 3.7: The DST offset is not restricted to a whole number of minutes.

datetime.tzname()

If tzinfo is None, returns None, else returns self.tzinfo.tzname(self), raises an exception if the latter doesn’t return None or a string object,

datetime.timetuple()

Return a time.struct_time such as returned by time.localtime(). d.timetuple() is equivalent to time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst)), where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st. The tm_isdst flag of the result is set according to the dst() method: tzinfo is None or dst() returns None, tm_isdst is set to -1; else if dst() returns a non-zero value, tm_isdst is set to 1; else tm_isdst is set to 0.

datetime.utctimetuple()

If datetime instance d is naive, this is the same as d.timetuple() except that tm_isdst is forced to 0 regardless of what d.dst() returns. DST is never in effect for a UTC time.

If d is aware, d is normalized to UTC time, by subtracting d.utcoffset(), and a time.struct_time for the normalized time is returned. tm_isdst is forced to 0. Note that an OverflowError may be raised if d.year was MINYEAR or MAXYEAR and UTC adjustment spills over a year boundary.

datetime.toordinal()

Return the proleptic Gregorian ordinal of the date. The same as self.date().toordinal().

datetime.timestamp()

Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time().

Naive datetime instances are assumed to represent local time and this method relies on the platform C mktime() function to perform the conversion. Since datetime supports wider range of values than mktime() on many platforms, this method may raise OverflowError for times far in the past or far in the future.

datetime.weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as self.date().weekday(). See also isoweekday().

datetime.isoweekday()

Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as self.date().isoweekday(). See also weekday(), isocalendar().

datetime.isocalendar()

Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as self.date().isocalendar().

datetime.isoformat(sep=’T’, timespec=’auto’)

Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.ffffff or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS

If utcoffset() does not return None, a string is appended, giving the UTC offset: YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]] or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]].

The optional argument sep (default ‘T’) is a one-character separator, placed between the date and time portions of the result. For example,

1
2
3
4
5
6
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

The optional argument timespec specifies the number of additional components of the time to include (the default is ‘auto’). It can be one of the following:

  • ‘auto’: Same as ‘seconds’ if microsecond is 0, same as ‘microseconds’ otherwise.

  • ‘hours’: Include the hour in the two-digit HH format.

  • ‘minutes’: Include hour and minute in HH:MM format.

  • ‘seconds’: Include hour, minute, and second in HH:MM:SS format.

  • ‘milliseconds’: Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format.

  • ‘microseconds’: Include full time in HH:MM:SS.ffffff format.

ValueError will be raised on an invalid timespec argument.

1
2
3
4
5
6
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes') # doctest: +SKIP
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'

datetime.str()

For a datetime instance d, str(d) is equivalent to d.isoformat(‘ ‘).

datetime.ctime()

Return a string representing the date and time, for example datetime(2002, 12, 4, 20, 30, 40).ctime() == ‘Wed Dec 4 20:30:40 2002’. d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())) on platforms where the native C ctime() function (which time.ctime() invokes, but which datetime.ctime() does not invoke) conforms to the C standard.

datetime.strftime(format)

Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.

datetime.format(format)

Same as datetime.strftime(). This makes it possible to specify a format string for a datetime object in formatted string literals and when using str.format(). For a complete list of formatting directives, see strftime() and strptime() Behavior.

Examples of working with datetime objects:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
>>> from datetime import datetime, date, time
>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using datetime.now() or datetime.utcnow()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
>>> datetime.utcnow()
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
... print(it)
...
2006 # year
11 # month
21 # day
16 # hour
30 # minute
0 # second
1 # weekday (0 = Monday)
325 # number of days since 1st January
-1 # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
... print(it)
...
2006 # ISO year
47 # ISO week
2 # ISO weekday
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'

Using datetime with tzinfo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
>>> from datetime import timedelta, datetime, tzinfo, timezone
>>> class KabulTz(tzinfo):
... # Kabul used +4 until 1945, when they moved to +4:30
... UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
... def utcoffset(self, dt):
... if dt.year < 1945:
... return timedelta(hours=4)
... elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
... # If dt falls in the imaginary range, use fold to decide how
... # to resolve. See PEP495
... return timedelta(hours=4, minutes=(30 if dt.fold else 0))
... else:
... return timedelta(hours=4, minutes=30)
...
... def fromutc(self, dt):
... # A custom implementation is required for fromutc as
... # the input to this function is a datetime with utc values
... # but with a tzinfo set to self
... # See datetime.astimezone or fromtimestamp
...
... # Follow same validations as in datetime.tzinfo
... if not isinstance(dt, datetime):
... raise TypeError("fromutc() requires a datetime argument")
... if dt.tzinfo is not self:
... raise ValueError("dt.tzinfo is not self")
...
... if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
... return dt + timedelta(hours=4, minutes=30)
... else:
... return dt + timedelta(hours=4)
...
... def dst(self, dt):
... return timedelta(0)
...
... def tzname(self, dt):
... if dt >= self.UTC_MOVE_DATE:
... return "+04:30"
... else:
... return "+04"
...
... def __repr__(self):
... return f"{self.__class__.__name__}()"
...
>>> tz1 = KabulTz()
>>> # Datetime before the change
>>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
>>> print(dt1.utcoffset())
4:00:00
>>> # Datetime after the change
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
>>> print(dt2.utcoffset())
4:30:00
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(timezone.utc)
>>> dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
>>> dt2.utctimetuple() == dt3.utctimetuple()
True

tzinfo Objects

1
class datetime.tzinfo
1
2
3
4
5
>>> from datetime import tzinfo

>>> dir(tzinfo)

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dst', 'fromutc', 'tzname', 'utcoffset']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Help on class tzinfo in module datetime:

class tzinfo(builtins.object)
| Abstract base class for time zone info objects.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| -> (cls, state)
|
| dst(...)
| datetime -> DST offset as timedelta positive east of UTC.
|
| fromutc(...)
| datetime in UTC -> datetime in local time.
|
| tzname(...)
| datetime -> string name of time zone.
|
| utcoffset(...)
| datetime -> timedelta showing offset from UTC, negative values indicating West of UTC
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

timezone Objects

The timezone class is a subclass of tzinfo, each instance of which represents a timezone defined by a fixed offset from UTC. Note that objects of this class cannot be used to represent timezone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time.

1
class datetime.timezone(offset, name=None)

The offset argument must be specified as a timedelta object representing the difference between the local time and UTC. It must be strictly between -timedelta(hours=24) and timedelta(hours=24), otherwise ValueError is raised.

The name argument is optional. If specified it must be a string that will be used as the value returned by the datetime.tzname() method.

1
2
3
4
>>> from datetime import timezone

>>> dir(timezone)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getinitargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dst', 'fromutc', 'max', 'min', 'tzname', 'utc', 'utcoffset']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Help on class timezone in module datetime:

class timezone(tzinfo)
| Fixed offset from UTC implementation of tzinfo.
|
| Method resolution order:
| timezone
| tzinfo
| builtins.object
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getinitargs__(...)
| pickle support
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __str__(self, /)
| Return str(self).
|
| dst(...)
| Return None.
|
| fromutc(...)
| datetime in UTC -> datetime in local time.
|
| tzname(...)
| If name is specified when timezone is created, returns the name. Otherwise returns offset as 'UTC(+|-)HH:MM'.
|
| utcoffset(...)
| Return fixed offset.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| max = datetime.timezone(datetime.timedelta(seconds=86340))
|
| min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
|
| utc = datetime.timezone.utc
|
| ----------------------------------------------------------------------
| Methods inherited from tzinfo:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| -> (cls, state)

Appendix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
格式	说明
%a 显示简化星期名称
%A 显示完整星期名称
%b 显示简化月份名称
%B 显示完整月份名称
%c 本地相应的日期和时间表示
%d 显示当月第几天
%H 按24小时制显示小时
%I 按12小时制显示小时
%j 显示当年第几天
%m 显示月份
%M 显示分钟数)
%p 本地am或者pm的相应符
%S 显示秒数)
%U 一年中的星期数
%w 显示在星期中的第几天,默认从0开始表示周一
%W 和%U基本相同
%x 本地相应日期
%X 本地相应时间
%y 去掉世纪的年份(00 - 99)
%Y 完整的年份
%Z 时区的名字(如果不存在为空字符)
%% ‘%’字符

summary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
NAME
datetime - Fast implementation of the datetime type.

CLASSES
builtins.object
date
datetime
time
timedelta
tzinfo
timezone

class date(builtins.object)
date(year, month, day) --> date object

td = date(year=2018, month=10, day=10) # td is instance of date

Instance Methods defined here:
ctime() # Return ctime() style string.
isocalendar() # Return a 3-tuple containing ISO year, week number, and weekday.
isoformat() # Return string in ISO 8601 format, YYYY-MM-DD.
isoweekday() # Return the day of the week represented by the date. Monday == 1 ... Sunday == 7
replace(year=self.year, month=self.month, day=self.day) # Return date with new specified fields.
strftime(format) # format -> strftime() style string.
timetuple() # Return time tuple, compatible with time.localtime().
toordinal() # Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.
weekday() # Return the day of the week represented by the date. Monday == 0 ... Sunday == 6

Class methods defined here:
fromisoformat(date_string)
from builtins.type
str -> Construct a date from the output of date.isoformat()

fromordinal(ordinal) from builtins.type
int -> date corresponding to a proleptic Gregorian ordinal.

fromtimestamp(timestamp) from builtins.type
timestamp -> local date from a POSIX timestamp (like time.time()).

today() from builtins.type
Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

Data descriptors defined here:
day
month
year

Data and other attributes defined here:
max = datetime.date(9999, 12, 31)
min = datetime.date(1, 1, 1)
resolution = datetime.timedelta(days=1)

class datetime(date)
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
The year, month and day arguments are required. tzinfo may be None, or an
instance of a tzinfo subclass. The remaining arguments may be ints.

Method resolution order:
datetime
date
builtins.object

Instance Methods defined here:
astimezone(tz=None) # tz -> convert to local time in new timezone tz
ctime() # Return ctime() style string.
date() # Return date object with same year, month and day.
dst() # Return self.tzinfo.dst(self).
isoformat(sep=’T’, timespec=’auto’)
[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
sep is used to separate the year from the time, and defaults to 'T'.
timespec specifies what components of the time to include (allowed values are 'auto', 'hours', 'minutes', 'seconds', 'milliseconds', and 'microseconds').
replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Return datetime with new specified fields.
time() # Return time object with same time but with tzinfo=None.
timestamp() # Return POSIX timestamp as float.
timetuple() # Return time tuple, compatible with time.localtime().
timetz() # Return time object with same time and tzinfo.
tzname() # Return self.tzinfo.tzname(self).
utcoffset() # Return self.tzinfo.utcoffset(self).
utctimetuple() # Return UTC time tuple, compatible with time.localtime().

Class methods defined here:
combine(date, time, tzinfo=self.tzinfo) from builtins.type
date, time -> datetime with same date and time fields

fromisoformat(date_string) from builtins.type
string -> datetime from datetime.isoformat() output

fromtimestamp(timestamp, tz=None) from builtins.type
timestamp[, tz] -> tz's local time from POSIX timestamp.
timestamp is 'datetime.datetime' object

now(tz=None) from builtins.type
Returns new datetime object representing current time local to tz.
tz
Timezone object.
If no tz is specified, uses local timezone.

strptime(date_string, format) from builtins.type
date_string, format -> new datetime parsed from a string (like time.strptime()).

utcfromtimestamp(timestamp) from builtins.type
Construct a naive UTC datetime from a POSIX timestamp.

utcnow() from builtins.type
Return a new datetime representing UTC day and time.

Data descriptors defined here:
fold
hour
microsecond
minute
second
tzinfo

Data and other attributes defined here:
max = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
min = datetime.datetime(1, 1, 1, 0, 0)
resolution = datetime.timedelta(microseconds=1)

Methods inherited from date:
isocalendar() # Return a 3-tuple containing ISO year, week number, and weekday.

isoweekday()
Return the day of the week represented by the date.
Monday == 1 ... Sunday == 7

strftime(format)
format -> strftime() style string.

toordinal()
Return proleptic Gregorian ordinal. January 1 of year 1 is day 1.

weekday()
Return the day of the week represented by the date.
Monday == 0 ... Sunday == 6

Class methods inherited from date:
fromordinal(ordinal) from builtins.type
int -> date corresponding to a proleptic Gregorian ordinal.

today() from builtins.type
Current date or datetime: same as self.__class__.fromtimestamp(time.time()).

Data descriptors inherited from date:
day
month
year

class time(builtins.object)
time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object

All arguments are optional. tzinfo may be None, or an instance of
a tzinfo subclass. The remaining arguments may be ints.

Methods defined here:
dst() # Return self.tzinfo.dst(self).

isoformat(timespec=’auto’)
Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
timespec specifies what components of the time to include.

replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
Return time with new specified fields.

strftime(format)
format -> strftime() style string.

tzname()
Return self.tzinfo.tzname(self).

utcoffset()
Return self.tzinfo.utcoffset(self).

Class methods defined here:
fromisoformat(time_string) from builtins.type
string -> time from time.isoformat() output

Data descriptors defined here:
fold
hour
microsecond
minute
second
tzinfo

Data and other attributes defined here:
max = datetime.time(23, 59, 59, 999999)
min = datetime.time(0, 0)
resolution = datetime.timedelta(microseconds=1)

class timedelta(builtins.object)
Difference between two datetime values.

Methods defined here:
total_seconds()
Total seconds in the duration.

Data descriptors defined here:
days # Number of days.
microseconds # Number of microseconds (>= 0 and less than 1 second).
seconds # Number of seconds (>= 0 and less than 1 day).

Data and other attributes defined here:
max = datetime.timedelta(days=999999999, seconds=86399, microseconds=9...
min = datetime.timedelta(days=-999999999)
resolution = datetime.timedelta(microseconds=1)

class timezone(tzinfo)
Fixed offset from UTC implementation of tzinfo.

Method resolution order:
timezone
tzinfo
builtins.object

Methods defined here:
dst() # Return None.
fromutc() # datetime in UTC -> datetime in local time.
tzname(...)
If name is specified when timezone is created, returns the name. Otherwise returns offset as 'UTC(+|-) HH:MM'.

utcoffset(...)
Return fixed offset.

Data and other attributes defined here:
max = datetime.timezone(datetime.timedelta(seconds=86340))
min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))
utc = datetime.timezone.utc


class tzinfo(builtins.object)
Abstract base class for time zone info objects.

Methods defined here:
dst(...)
datetime -> DST offset as timedelta positive east of UTC.

fromutc(...)
datetime in UTC -> datetime in local time.

tzname(...)
datetime -> string name of time zone.

utcoffset(...)
datetime -> timedelta showing offset from UTC, negative values indicating West of UTC

DATA
MAXYEAR = 9999
MINYEAR = 1
datetime_CAPI = <capsule object "datetime.datetime_CAPI">
-------------本文结束感谢您的阅读-------------