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 | >>> import datetime |
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 | >>> from datetime import timedelta |
Class attributes
timedelta.min
The most negative timedelta object, timedelta(-999999999).
1 | >>> timedelta.min |
timedelta.max
The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
1 | >>> timedelta.max |
timedelta.resolution
The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1).
1 | >>> timedelta.resolution |
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 | >>> from datetime import timedelta |
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 | from datetime import timedelta |
Supported operations
1 | >>> from datetime import timedelta |
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 | >>> from datetime import date |
Class attributes
date.min
The earliest representable date, date(MINYEAR, 1, 1).
1 | >>> from datetime import date |
date.max
The latest representable date, date(MAXYEAR, 12, 31).
1 | >>> from datetime import date |
date.resolution
The smallest possible difference between non-equal date objects, timedelta(days=1).
1 | >>> from datetime import date |
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 | >>> from datetime import date |
date.fromtimestamp(timestamp)
Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
1 | >>> import time |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.
For example
1 | >>> from datetime import date |
date.__str__()
For a date d, str(d) is equivalent to d.isoformat().
1 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import date |
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 | >>> from datetime import time |
Class attributes
time.min
The earliest representable time, time(0, 0, 0, 0).
1 | >>> from datetime import time |
time.max
The latest representable time, time(23, 59, 59, 999999).
1 | >>> from datetime import time |
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 | >>> from datetime import time |
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 | >>> from datetime import time |
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 | >>> from datetime import time |
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 | >>> from datetime import time |
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 | >>> from datetime import time, tzinfo, timedelta |
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 | >>> from datetime import datetime |
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 | >>> from datetime import datetime |
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 | >>> from datetime import tzinfo, timedelta, datetime |
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 | >>> from datetime import datetime |
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 | >>> from datetime import datetime, date, time |
Using datetime with tzinfo:
1 | >>> from datetime import timedelta, datetime, tzinfo, timezone |
tzinfo Objects
1 | class datetime.tzinfo |
1 | >>> from datetime import tzinfo |
1 | Help on class tzinfo in module datetime: |
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 | >>> from datetime import timezone |
1 | Help on class timezone in module datetime: |
Appendix
1 | 格式 说明 |
summary
1 | NAME |