A
datetime
object is a single object containing all the information from a
date
object and a
time
对象。
Like a
date
对象,
datetime
assumes the current Gregorian calendar extended in both directions; like a
time
对象,
datetime
assumes there are exactly 3600*24 seconds in every day.
构造函数:
-
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
可以是
None
, or an instance of a
tzinfo
subclass. The remaining arguments must 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]
.
若给定自变量在那些范围之外,
ValueError
被引发。
3.6 版改变:
添加
fold
参数。
其它构造函数,所有类方法:
-
classmethod
datetime.
today
(
)
¶
-
Return the current local date and time, with
tzinfo
None
.
等效于:
datetime.fromtimestamp(time.time())
另请参阅
now()
,
fromtimestamp()
.
This method is functionally equivalent to
now()
, but without a
tz
参数。
-
classmethod
datetime.
now
(
tz
=
None
)
¶
-
Return the current local date and time.
若可选自变量
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()
函数)。
若
tz
不是
None
, it must be an instance of a
tzinfo
subclass, and the current date and time are converted to
tz
’s time zone.
This function is preferred over
today()
and
utcnow()
.
注意
Subsequent calls to
datetime.now()
may return the same instant depending on the precision of the underlying clock.
-
classmethod
datetime.
utcnow
(
)
¶
-
Return the current UTC date and time, with
tzinfo
None
.
这像
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)
。另请参阅
now()
.
警告
Because naive
datetime
objects are treated by many
datetime
methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling
datetime.now(timezone.utc)
.
-
classmethod
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.
若
tz
不是
None
, it must be an instance of a
tzinfo
subclass, and the timestamp is converted to
tz
’s time zone.
fromtimestamp()
可能引发
OverflowError
, if the timestamp is out of the range of values supported by the platform C
localtime()
or
gmtime()
functions, and
OSError
on
localtime()
or
gmtime()
failure. It’s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by
fromtimestamp()
, and then it’s possible to have two timestamps differing by a second that yield identical
datetime
objects. This method is preferred over
utcfromtimestamp()
.
3.3 版改变:
引发
OverflowError
而不是
ValueError
if the timestamp is out of the range of values supported by the platform C
localtime()
or
gmtime()
functions. Raise
OSError
而不是
ValueError
on
localtime()
or
gmtime()
故障。
3.6 版改变:
fromtimestamp()
may return instances with
fold
set to 1.
-
classmethod
datetime.
utcfromtimestamp
(
timestamp
)
¶
-
Return the UTC
datetime
corresponding to the POSIX timestamp, with
tzinfo
None
. (The resulting object is naive.)
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.
To get an aware
datetime
对象,调用
fromtimestamp()
:
datetime.fromtimestamp(timestamp, timezone.utc)
On the POSIX compliant platforms, it is equivalent to the following expression:
datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
except the latter formula always supports the full years range: between
MINYEAR
and
MAXYEAR
包括在内。
警告
Because naive
datetime
objects are treated by many
datetime
methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing a specific timestamp in UTC is by calling
datetime.fromtimestamp(timestamp, tz=timezone.utc)
.
3.3 版改变:
引发
OverflowError
而不是
ValueError
if the timestamp is out of the range of values supported by the platform C
gmtime()
函数。引发
OSError
而不是
ValueError
on
gmtime()
故障。
-
classmethod
datetime.
fromordinal
(
ordinal
)
¶
-
返回
datetime
corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
ValueError
被引发除非
1 <= ordinal <= datetime.max.toordinal()
. The hour, minute, second and microsecond of the result are all 0, and
tzinfo
is
None
.
-
classmethod
datetime.
combine
(
date
,
time
,
tzinfo
=
time.tzinfo
)
¶
-
返回新的
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
属性在
time
argument is used. If the
date
自变量是
datetime
object, its time components and
tzinfo
attributes are ignored.
For any
datetime
对象
d
,
d == datetime.combine(d.date(), d.time(), d.tzinfo)
.
3.6 版改变:
添加
tzinfo
自变量。
-
classmethod
datetime.
fromisoformat
(
date_string
)
¶
-
返回
datetime
corresponding to a
date_string
in any valid ISO 8601 format, with the following exceptions:
-
Time zone offsets may have fractional seconds.
-
The
T
separator may be replaced by any single unicode character.
-
Fractional hours and minutes are not supported.
-
Reduced precision dates are not currently supported (
YYYY-MM
,
YYYY
).
-
Extended date representations are not currently supported (
±YYYYYY-MM-DD
).
-
Ordinal dates are not currently supported (
YYYY-OOO
).
范例:
>>> from datetime import datetime
>>> datetime.fromisoformat('2011-11-04')
datetime.datetime(2011, 11, 4, 0, 0)
>>> datetime.fromisoformat('20111104')
datetime.datetime(2011, 11, 4, 0, 0)
>>> datetime.fromisoformat('2011-11-04T00:05:23')
datetime.datetime(2011, 11, 4, 0, 5, 23)
>>> datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('20111104T000523')
datetime.datetime(2011, 11, 4, 0, 5, 23)
>>> datetime.fromisoformat('2011-W01-2T00:05:23.283')
datetime.datetime(2011, 1, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000)
>>> datetime.fromisoformat('2011-11-04 00:05:23.283+00:00')
datetime.datetime(2011, 11, 4, 0, 5, 23, 283000, tzinfo=datetime.timezone.utc)
>>> datetime.fromisoformat('2011-11-04T00:05:23+04:00')
datetime.datetime(2011, 11, 4, 0, 5, 23,
tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
3.7 版添加。
3.11 版改变:
Previously, this method only supported formats that could be emitted by
date.isoformat()
or
datetime.isoformat()
.
-
classmethod
datetime.
fromisocalendar
(
year
,
week
,
day
)
¶
-
返回
datetime
corresponding to the ISO calendar date specified by year, week and day. The non-date components of the datetime are populated with their normal default values. This is the inverse of the function
datetime.isocalendar()
.
Added in version 3.8.
-
classmethod
datetime.
strptime
(
date_string
,
format
)
¶
-
返回
datetime
对应
date_string
, parsed according to
format
.
若
format
does not contain microseconds or time zone information, 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. See also
strftime() 和 strptime() 行为
and
datetime.fromisoformat()
.
Changed in version 3.13:
若
format
specifies a day of month without a year a
DeprecationWarning
is now emitted. This is to avoid a quadrennial leap year bug in code seeking to parse only a month and day as the default year used in absence of one in the format is not a leap year. Such
format
values may raise an error as of Python 3.15. The workaround is to always include a year in your
format
. If parsing
date_string
values that do not have a year, explicitly add a year that is a leap year before parsing:
>>> from datetime import datetime
>>> date_string = "02/29"
>>> when = datetime.strptime(f"{date_string};1984", "%m/%d;%Y") # Avoids leap year bug.
>>> when.strftime("%B %d")
'February 29'
类属性:
-
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
¶
-
最小可能差异介于不相等
datetime
对象,
timedelta(microseconds=1)
.
实例属性 (只读):
-
datetime.
year
¶
-
介于
MINYEAR
and
MAXYEAR
包括在内。
-
datetime.
month
¶
-
在 1 至 12 (包括在内) 之间。
-
datetime.
day
¶
-
Between 1 and the number of days in the given month of the given year.
-
datetime.
hour
¶
-
在
range(24)
.
-
datetime.
minute
¶
-
在
range(60)
.
-
datetime.
second
¶
-
在
range(60)
.
-
datetime.
microsecond
¶
-
在
range(1000000)
.
-
datetime.
tzinfo
¶
-
The object passed as the
tzinfo
自变量到
datetime
constructor, or
None
if none was passed.
-
datetime.
fold
¶
-
在
[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 values 0 and 1 represent, respectively, the earlier and later of the two moments with the same wall time representation.
Added in version 3.6.
支持的操作:
|
操作
|
结果
|
|
datetime2 = datetime1 + timedelta
|
(1)
|
|
datetime2 = datetime1 - timedelta
|
(2)
|
|
timedelta = datetime1 - datetime2
|
(3)
|
datetime1 == datetime2
datetime1 != datetime2
|
Equality comparison. (4)
|
datetime1 < datetime2
datetime1 > datetime2
datetime1 <= datetime2
datetime1 >= datetime2
|
Order comparison. (5)
|
-
datetime2
is a duration of
timedelta
removed from
datetime1
, moving forward in time if
timedelta.days > 0
, or backward if
timedelta.days < 0
. The result has the same
tzinfo
attribute as the input datetime, and
datetime2 - datetime1 == timedelta
after.
OverflowError
被引发若
datetime2.year
将小于
MINYEAR
或大于
MAXYEAR
. Note that no time zone adjustments are done even if the input is an aware object.
-
Computes the
datetime2
这样
datetime2 + timedelta == datetime1
. As for addition, the result has the same
tzinfo
attribute as the input datetime, and no time zone adjustments are done even if the input is aware.
-
Subtraction of a
datetime
从
datetime
is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive,
TypeError
被引发。
If both are naive, or both are aware and have the same
tzinfo
attribute, the
tzinfo
attributes are ignored, and the result is a
timedelta
对象
t
这样
datetime2 + t == datetime1
. No time zone adjustments are done in this case.
If both are aware and have different
tzinfo
attributes,
a-b
acts as if
a
and
b
were first converted to naive UTC datetimes. The result is
(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
- b.utcoffset())
except that the implementation never overflows.
-
datetime
objects are equal if they represent the same date and time, taking into account the time zone.
Naive and aware
datetime
objects are never equal.
If both comparands are aware, and have the same
tzinfo
attribute, the
tzinfo
and
fold
attributes are ignored and the base datetimes are compared. If both comparands are aware and have different
tzinfo
attributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows.
datetime
instances in a repeated interval are never equal to
datetime
instances in other time zone.
-
datetime1
被认为小于
datetime2
当
datetime1
precedes
datetime2
in time, taking into account the time zone.
Order comparison between naive and aware
datetime
objects raises
TypeError
.
If both comparands are aware, and have the same
tzinfo
attribute, the
tzinfo
and
fold
attributes are ignored and the base datetimes are compared. If both comparands are aware and have different
tzinfo
attributes, the comparison acts as comparands were first converted to UTC datetimes except that the implementation never overflows.
3.3 版改变:
Equality comparisons between aware and naive
datetime
instances don’t raise
TypeError
.
Changed in version 3.13:
Comparison between
datetime
object and an instance of the
date
subclass that is not a
datetime
subclass no longer converts the latter to
date
, ignoring the time part and the time zone. The default behavior can be changed by overriding the special comparison methods in subclasses.
实例方法:
-
datetime.
date
(
)
¶
-
返回
date
object with same year, month and day.
-
datetime.
time
(
)
¶
-
返回
time
object with same hour, minute, second, microsecond and fold.
tzinfo
is
None
. See also method
timetz()
.
3.6 版改变:
The fold value is copied to the returned
time
对象。
-
datetime.
timetz
(
)
¶
-
返回
time
object with same hour, minute, second, microsecond, fold, and tzinfo attributes. See also method
time()
.
3.6 版改变:
The fold value is copied to the returned
time
对象。
-
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.
datetime
objects are also supported by generic function
copy.replace()
.
3.6 版改变:
添加
fold
参数。
-
datetime.
astimezone
(
tz
=
None
)
¶
-
返回
datetime
object with new
tzinfo
属性
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
。若
self
is naive, it is presumed to represent time in the system time zone.
If called without arguments (or with
tz=None
) the system local time zone is assumed for the target time zone. The
.tzinfo
attribute of the converted datetime instance will be set to an instance of
timezone
with the zone name and offset obtained from the OS.
若
self.tzinfo
is
tz
,
self.astimezone(tz)
等于
self
: no adjustment of date or time data is performed. Else the result is local time in the time zone
tz
, representing the same UTC time as
self
: after
astz = dt.astimezone(tz)
,
astz - astz.utcoffset()
will have the same date and time data as
dt - dt.utcoffset()
.
If you merely want to attach a
timezone
对象
tz
to a datetime
dt
without adjustment of date and time data, use
dt.replace(tzinfo=tz)
. If you merely want to remove the
timezone
object from an aware datetime
dt
without conversion of date and time data, use
dt.replace(tzinfo=None)
.
Note that the default
tzinfo.fromutc()
method can be overridden in a
tzinfo
subclass to affect the result returned by
astimezone()
. Ignoring error cases,
astimezone()
acts like:
def astimezone(self, tz):
if self.tzinfo is tz:
return self
# Convert self to UTC, and attach the new timezone object.
utc = (self - self.utcoffset()).replace(tzinfo=tz)
# Convert from UTC to tz's local time.
return tz.fromutc(utc)
3.3 版改变:
tz
now can be omitted.
3.6 版改变:
The
astimezone()
method can now be called on naive instances that are presumed to represent system local time.
-
datetime.
utcoffset
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.utcoffset(self)
, and raises an exception if the latter doesn’t return
None
或
timedelta
object with magnitude less than one day.
3.7 版改变:
The UTC offset is not restricted to a whole number of minutes.
-
datetime.
dst
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.dst(self)
, and raises an exception if the latter doesn’t return
None
或
timedelta
object with magnitude less than one day.
3.7 版改变:
The DST offset is not restricted to a whole number of minutes.
-
datetime.
tzname
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.tzname(self)
, raises an exception if the latter doesn’t return
None
or a string object,
-
datetime.
timetuple
(
)
¶
-
返回
time.struct_time
譬如返回通过
time.localtime()
.
d.timetuple()
相当于:
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()
方法:
tzinfo
is
None
or
dst()
返回
None
,
tm_isdst
被设为
-1
;否则若
dst()
返回非 0 值,
tm_isdst
is set to 1; else
tm_isdst
is set to 0.
-
datetime.
utctimetuple
(
)
¶
-
若
datetime
实例
d
is naive, this is the same as
d.timetuple()
除了
tm_isdst
is forced to 0 regardless of what
d.dst()
returns. DST is never in effect for a UTC time.
若
d
is aware,
d
is normalized to UTC time, by subtracting
d.utcoffset()
,和
time.struct_time
for the normalized time is returned.
tm_isdst
is forced to 0. Note that an
OverflowError
可能被引发若
d.year
was
MINYEAR
or
MAXYEAR
and UTC adjustment spills over a year boundary.
警告
Because naive
datetime
objects are treated by many
datetime
methods as local times, it is preferred to use aware datetimes to represent times in UTC; as a result, using
datetime.utctimetuple()
may give misleading results. If you have a naive
datetime
representing UTC, use
datetime.replace(tzinfo=timezone.utc)
to make it aware, at which point you can use
datetime.timetuple()
.
-
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
or
OSError
for times far in the past or far in the future.
For aware
datetime
instances, the return value is computed as:
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
Added in version 3.3.
3.6 版改变:
The
timestamp()
method uses the
fold
attribute to disambiguate the times during a repeated interval.
注意
There is no method to obtain the POSIX timestamp directly from a naive
datetime
instance representing UTC time. If your application uses this convention and your system time zone is not set to UTC, you can obtain the POSIX timestamp by supplying
tzinfo=timezone.utc
:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
or by calculating the timestamp directly:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
-
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()
。另请参阅
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()
。另请参阅
weekday()
,
isocalendar()
.
-
datetime.
isocalendar
(
)
¶
-
返回
命名元组
with three components:
year
,
week
and
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:
若
utcoffset()
不返回
None
, a string is appended, giving the UTC offset:
范例:
>>> from datetime import datetime, timezone
>>> datetime(2019, 5, 18, 15, 17, 8, 132263).isoformat()
'2019-05-18T15:17:08.132263'
>>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00+00:00'
可选自变量
sep
(默认
'T'
) is a one-character separator, placed between the date and time portions of the result. For example:
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... """A time zone with an arbitrary, constant -06:39 offset."""
... def utcoffset(self, dt):
... return timedelta(hours=-6, minutes=-39)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
>>> datetime(2009, 11, 27, microsecond=100, tzinfo=TZ()).isoformat()
'2009-11-27T00:00:00.000100-06:39'
可选自变量
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'
否则。
-
'hours'
: Include the
hour
in the two-digit
HH
格式。
-
'minutes'
: Include
hour
and
minute
in
HH:MM
格式。
-
'seconds'
: Include
hour
,
minute
,和
second
in
HH:MM:SS
格式。
-
'milliseconds'
: Include full time, but truncate fractional second part to milliseconds.
HH:MM:SS.sss
格式。
-
'microseconds'
: Include full time in
HH:MM:SS.ffffff
格式。
注意
Excluded time components are truncated, not rounded.
ValueError
will be raised on an invalid
timespec
自变量:
>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'
3.6 版改变:
添加
timespec
参数。
-
datetime.
__str__
(
)
¶
-
对于
datetime
实例
d
,
str(d)
相当于
d.isoformat(' ')
.
-
datetime.
ctime
(
)
¶
-
Return a string representing the date and time:
>>> from datetime import datetime
>>> datetime(2002, 12, 4, 20, 30, 40).ctime()
'Wed Dec 4 20:30:40 2002'
The output string will
not
include time zone information, regardless of whether the input is aware or naive.
d.ctime()
相当于:
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. See also
strftime() 和 strptime() 行为
and
datetime.isoformat()
.
-
datetime.
__format__
(
format
)
¶
-
如同
datetime.strftime()
. This makes it possible to specify a format string for a
datetime
object in
格式化字符串文字
and when using
str.format()
。另请参阅
strftime() 和 strptime() 行为
and
datetime.isoformat()
.
Examples of working with
datetime
对象:
>>> from datetime import datetime, date, time, timezone
>>> # 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()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1
>>> datetime.now(timezone.utc)
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060, tzinfo=datetime.timezone.utc)
>>> # 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 a 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.'
The example below defines a
tzinfo
subclass capturing time zone information for Kabul, Afghanistan, which used +4 UTC until 1945 and then +4:30 UTC thereafter:
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):
# An ambiguous ("imaginary") half-hour range representing
# a 'fold' in time due to the shift from +4 to +4: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):
# 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")
# 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.
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):
# Kabul does not observe daylight saving time.
return timedelta(0)
def tzname(self, dt):
if dt >= self.UTC_MOVE_DATE:
return "+04:30"
return "+04"
Usage of
KabulTz
from above:
>>> 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 == dt3
True
A
time
object represents a (local) time of day, independent of any particular day, and subject to adjustment via a
tzinfo
对象。
-
class
datetime.
time
(
hour
=
0
,
minute
=
0
,
second
=
0
,
microsecond
=
0
,
tzinfo
=
None
,
*
,
fold
=
0
)
¶
-
All arguments are optional.
tzinfo
可以是
None
, or an instance of a
tzinfo
subclass. The remaining arguments must be integers in the following ranges:
若给定自变量在那些范围之外,
ValueError
is raised. All default to 0 except
tzinfo
,其默认为
None
.
类属性:
-
time.
min
¶
-
The earliest representable
time
,
time(0, 0, 0, 0)
.
-
time.
max
¶
-
The latest representable
time
,
time(23, 59, 59, 999999)
.
-
time.
resolution
¶
-
最小可能差异介于不相等
time
对象,
timedelta(microseconds=1)
, although note that arithmetic on
time
objects is not supported.
实例属性 (只读):
-
time.
hour
¶
-
在
range(24)
.
-
time.
minute
¶
-
在
range(60)
.
-
time.
second
¶
-
在
range(60)
.
-
time.
microsecond
¶
-
在
range(1000000)
.
-
time.
tzinfo
¶
-
The object passed as the tzinfo argument to the
time
constructor, or
None
if none was passed.
-
time.
fold
¶
-
在
[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 values 0 and 1 represent, respectively, the earlier and later of the two moments with the same wall time representation.
Added in version 3.6.
time
objects support equality and order comparisons, where
a
被认为小于
b
当
a
precedes
b
in time.
Naive and aware
time
objects are never equal. Order comparison between naive and aware
time
objects raises
TypeError
.
If both comparands are aware, and have the same
tzinfo
attribute, the
tzinfo
and
fold
attributes are ignored and the base times are compared. If both comparands are aware and have different
tzinfo
attributes, the comparands are first adjusted by subtracting their UTC offsets (obtained from
self.utcoffset()
).
3.3 版改变:
Equality comparisons between aware and naive
time
instances don’t raise
TypeError
.
在布尔上下文,
time
object is always considered to be true.
3.5 版改变:
Before Python 3.5, a
time
object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See
bpo-13936
for full details.
Other constructor:
-
classmethod
time.
fromisoformat
(
time_string
)
¶
-
返回
time
corresponding to a
time_string
in any valid ISO 8601 format, with the following exceptions:
-
Time zone offsets may have fractional seconds.
-
The leading
T
, normally required in cases where there may be ambiguity between a date and a time, is not required.
-
Fractional seconds may have any number of digits (anything beyond 6 will be truncated).
-
Fractional hours and minutes are not supported.
范例:
>>> from datetime import time
>>> time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
>>> time.fromisoformat('T04:23:01')
datetime.time(4, 23, 1)
>>> time.fromisoformat('T042301')
datetime.time(4, 23, 1)
>>> time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
>>> time.fromisoformat('04:23:01,000384')
datetime.time(4, 23, 1, 384)
>>> time.fromisoformat('04:23:01+04:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
>>> time.fromisoformat('04:23:01Z')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
>>> time.fromisoformat('04:23:01+00:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone.utc)
3.7 版添加。
3.11 版改变:
Previously, this method only supported formats that could be emitted by
time.isoformat()
.
实例方法:
-
time.
replace
(
hour
=
self.hour
,
minute
=
self.minute
,
second
=
self.second
,
microsecond
=
self.microsecond
,
tzinfo
=
self.tzinfo
,
*
,
fold
=
0
)
¶
-
返回
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.
time
objects are also supported by generic function
copy.replace()
.
3.6 版改变:
添加
fold
参数。
-
time.
isoformat
(
timespec
=
'auto'
)
¶
-
Return a string representing the time in ISO 8601 format, one of:
可选自变量
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'
否则。
-
'hours'
: Include the
hour
in the two-digit
HH
格式。
-
'minutes'
: Include
hour
and
minute
in
HH:MM
格式。
-
'seconds'
: Include
hour
,
minute
,和
second
in
HH:MM:SS
格式。
-
'milliseconds'
: Include full time, but truncate fractional second part to milliseconds.
HH:MM:SS.sss
格式。
-
'microseconds'
: Include full time in
HH:MM:SS.ffffff
格式。
注意
Excluded time components are truncated, not rounded.
ValueError
will be raised on an invalid
timespec
自变量。
范例:
>>> from datetime import time
>>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
'12:34'
>>> dt = time(hour=12, minute=34, second=56, microsecond=0)
>>> dt.isoformat(timespec='microseconds')
'12:34:56.000000'
>>> dt.isoformat(timespec='auto')
'12:34:56'
3.6 版改变:
添加
timespec
参数。
-
time.
__str__
(
)
¶
-
For a time
t
,
str(t)
相当于
t.isoformat()
.
-
time.
strftime
(
format
)
¶
-
Return a string representing the time, controlled by an explicit format string. See also
strftime() 和 strptime() 行为
and
time.isoformat()
.
-
time.
__format__
(
format
)
¶
-
如同
time.strftime()
. This makes it possible to specify a format string for a
time
object in
格式化字符串文字
and when using
str.format()
。另请参阅
strftime() 和 strptime() 行为
and
time.isoformat()
.
-
time.
utcoffset
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.utcoffset(None)
, and raises an exception if the latter doesn’t return
None
或
timedelta
object with magnitude less than one day.
3.7 版改变:
The UTC offset is not restricted to a whole number of minutes.
-
time.
dst
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.dst(None)
, and raises an exception if the latter doesn’t return
None
,或
timedelta
object with magnitude less than one day.
3.7 版改变:
The DST offset is not restricted to a whole number of minutes.
-
time.
tzname
(
)
¶
-
若
tzinfo
is
None
,返回
None
, else returns
self.tzinfo.tzname(None)
, or raises an exception if the latter doesn’t return
None
or a string object.
Examples of working with a
time
对象:
>>> 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.'
-
class
datetime.
tzinfo
¶
-
This is an abstract base class, meaning that this class should not be instantiated directly. Define a subclass of
tzinfo
to capture information about a particular time zone.
An instance of (a concrete subclass of)
tzinfo
can be passed to the constructors for
datetime
and
time
objects. The latter objects view their attributes as being in local time, and the
tzinfo
object supports methods revealing offset of local time from UTC, the name of the time zone, and DST offset, all relative to a date or time object passed to them.
You need to derive a concrete subclass, and (at least) supply implementations of the standard
tzinfo
methods needed by the
datetime
methods you use. The
datetime
模块提供
timezone
, a simple concrete subclass of
tzinfo
which can represent time zones with fixed offset from UTC such as UTC itself or North American EST and EDT.
Special requirement for pickling: A
tzinfo
subclass must have an
__init__()
method that can be called with no arguments, otherwise it can be pickled but possibly not unpickled again. This is a technical requirement that may be relaxed in the future.
A concrete subclass of
tzinfo
may need to implement the following methods. Exactly which methods are needed depends on the uses made of aware
datetime
objects. If in doubt, simply implement all of them.
-
tzinfo.
utcoffset
(
dt
)
¶
-
Return offset of local time from UTC, as a
timedelta
object that is positive east of UTC. If local time is west of UTC, this should be negative.
This represents the
total
offset from UTC; for example, if a
tzinfo
object represents both time zone and DST adjustments,
utcoffset()
should return their sum. If the UTC offset isn’t known, return
None
. Else the value returned must be a
timedelta
object strictly between
-timedelta(hours=24)
and
timedelta(hours=24)
(the magnitude of the offset must be less than one day). Most implementations of
utcoffset()
will probably look like one of these two:
return CONSTANT # fixed-offset class
return CONSTANT + self.dst(dt) # daylight-aware class
若
utcoffset()
不返回
None
,
dst()
should not return
None
either.
默认实现的
utcoffset()
引发
NotImplementedError
.
3.7 版改变:
The UTC offset is not restricted to a whole number of minutes.
-
tzinfo.
dst
(
dt
)
¶
-
Return the daylight saving time (DST) adjustment, as a
timedelta
object or
None
if DST information isn’t known.
返回
timedelta(0)
if DST is not in effect. If DST is in effect, return the offset as a
timedelta
object (see
utcoffset()
for details). Note that DST offset, if applicable, has already been added to the UTC offset returned by
utcoffset()
, so there’s no need to consult
dst()
unless you’re interested in obtaining DST info separately. For example,
datetime.timetuple()
calls its
tzinfo
attribute’s
dst()
method to determine how the
tm_isdst
flag should be set, and
tzinfo.fromutc()
调用
dst()
to account for DST changes when crossing time zones.
An instance
tz
的
tzinfo
subclass that models both standard and daylight times must be consistent in this sense:
tz.utcoffset(dt) - tz.dst(dt)
must return the same result for every
datetime
dt
with
dt.tzinfo ==
tz
. For sane
tzinfo
subclasses, this expression yields the time zone’s “standard offset”, which should not depend on the date or the time, but only on geographic location. The implementation of
datetime.astimezone()
relies on this, but cannot detect violations; it’s the programmer’s responsibility to ensure it. If a
tzinfo
subclass cannot guarantee this, it may be able to override the default implementation of
tzinfo.fromutc()
to work correctly with
astimezone()
regardless.
Most implementations of
dst()
will probably look like one of these two:
def dst(self, dt):
# a fixed-offset class: doesn't account for DST
return timedelta(0)
或:
def dst(self, dt):
# Code to set dston and dstoff to the time zone's DST
# transition times based on the input dt.year, and expressed
# in standard local time.
if dston <= dt.replace(tzinfo=None) < dstoff:
return timedelta(hours=1)
else:
return timedelta(0)
默认实现的
dst()
引发
NotImplementedError
.
3.7 版改变:
The DST offset is not restricted to a whole number of minutes.
-
tzinfo.
tzname
(
dt
)
¶
-
Return the time zone name corresponding to the
datetime
对象
dt
, as a string. Nothing about string names is defined by the
datetime
module, and there’s no requirement that it mean anything in particular. For example,
"GMT"
,
"UTC"
,
"-500"
,
"-5:00"
,
"EDT"
,
"US/Eastern"
,
"America/New York"
are all valid replies. Return
None
if a string name isn’t known. Note that this is a method rather than a fixed string primarily because some
tzinfo
subclasses will wish to return different names depending on the specific value of
dt
passed, especially if the
tzinfo
class is accounting for daylight time.
默认实现的
tzname()
引发
NotImplementedError
.
These methods are called by a
datetime
or
time
object, in response to their methods of the same names. A
datetime
object passes itself as the argument, and a
time
object passes
None
as the argument. A
tzinfo
subclass’s methods should therefore be prepared to accept a
dt
自变量
None
, or of class
datetime
.
当
None
is passed, it’s up to the class designer to decide the best response. For example, returning
None
is appropriate if the class wishes to say that time objects don’t participate in the
tzinfo
protocols. It may be more useful for
utcoffset(None)
to return the standard UTC offset, as there is no other convention for discovering the standard offset.
当
datetime
object is passed in response to a
datetime
方法,
dt.tzinfo
is the same object as
self
.
tzinfo
methods can rely on this, unless user code calls
tzinfo
methods directly. The intent is that the
tzinfo
methods interpret
dt
as being in local time, and not need worry about objects in other time zones.
There is one more
tzinfo
method that a subclass may wish to override:
-
tzinfo.
fromutc
(
dt
)
¶
-
This is called from the default
datetime.astimezone()
implementation. When called from that,
dt.tzinfo
is
self
,和
dt
’s date and time data are to be viewed as expressing a UTC time. The purpose of
fromutc()
is to adjust the date and time data, returning an equivalent datetime in
self
’s local time.
Most
tzinfo
subclasses should be able to inherit the default
fromutc()
implementation without problems. It’s strong enough to handle fixed-offset time zones, and time zones accounting for both standard and daylight time, and the latter even if the DST transition times differ in different years. An example of a time zone the default
fromutc()
implementation may not handle correctly in all cases is one where the standard offset (from UTC) depends on the specific date and time passed, which can happen for political reasons. The default implementations of
astimezone()
and
fromutc()
may not produce the result you want if the result is one of the hours straddling the moment the standard offset changes.
Skipping code for error cases, the default
fromutc()
implementation acts like:
def fromutc(self, dt):
# raise ValueError error if dt.tzinfo is not self
dtoff = dt.utcoffset()
dtdst = dt.dst()
# raise ValueError if dtoff is None or dtdst is None
delta = dtoff - dtdst # this is self's standard offset
if delta:
dt += delta # convert to standard local time
dtdst = dt.dst()
# raise ValueError if dtdst is None
if dtdst:
return dt + dtdst
else:
return dt
In the following
tzinfo_examples.py
file there are some examples of
tzinfo
类:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)
# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
# timezones where UTC offset and/or the DST rules had
# changed in the past.)
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
def fromutc(self, dt):
assert dt.tzinfo is self
stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
args = _time.localtime(stamp)[:6]
dst_diff = DSTDIFF // SECOND
# Detect fold
fold = (args == _time.localtime(stamp - dst_diff))
return datetime(*args, microsecond=dt.microsecond,
tzinfo=self, fold=fold)
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, 0)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# https://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006
def us_dst_range(year):
# Find start and end times for US DST. For years before 1967, return
# start = end for no DST.
if 2006 < year:
dststart, dstend = DSTSTART_2007, DSTEND_2007
elif 1986 < year < 2007:
dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
elif 1966 < year < 1987:
dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
else:
return (datetime(year, 1, 1), ) * 2
start = first_sunday_on_or_after(dststart.replace(year=year))
end = first_sunday_on_or_after(dstend.replace(year=year))
return start, end
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
start, end = us_dst_range(dt.year)
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
dt = dt.replace(tzinfo=None)
if start + HOUR <= dt < end - HOUR:
# DST is in effect.
return HOUR
if end - HOUR <= dt < end:
# Fold (an ambiguous hour): use dt.fold to disambiguate.
return ZERO if dt.fold else HOUR
if start <= dt < start + HOUR:
# Gap (a non-existent hour): reverse the fold rule.
return HOUR if dt.fold else ZERO
# DST is off.
return ZERO
def fromutc(self, dt):
assert dt.tzinfo is self
start, end = us_dst_range(dt.year)
start = start.replace(tzinfo=self)
end = end.replace(tzinfo=self)
std_time = dt + self.stdoffset
dst_time = std_time + HOUR
if end <= dst_time < end + HOUR:
# Repeated hour
return std_time.replace(fold=1)
if std_time < start or dst_time >= end:
# Standard time
return std_time
if start <= std_time < end - HOUR:
# Daylight saving time
return dst_time
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
Note that there are unavoidable subtleties twice per year in a
tzinfo
subclass accounting for both standard and daylight time, at the DST transition points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 1:59 (EDT) on the first Sunday in November:
UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM
EST 22:MM 23:MM 0:MM 1:MM 2:MM 3:MM
EDT 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
start 22:MM 23:MM 0:MM 1:MM 3:MM 4:MM
end 23:MM 0:MM 1:MM 1:MM 2:MM 3:MM
When DST starts (the “start” line), the local wall clock leaps from 1:59 to 3:00. A wall time of the form 2:MM doesn’t really make sense on that day, so
astimezone(Eastern)
won’t deliver a result with
hour == 2
on the day DST begins. For example, at the Spring forward transition of 2016, we get:
>>> from datetime import datetime, timezone
>>> from tzinfo_examples import HOUR, Eastern
>>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
>>> for i in range(4):
... u = u0 + i*HOUR
... t = u.astimezone(Eastern)
... print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT
When DST ends (the “end” line), there’s a potentially worse problem: there’s an hour that can’t be spelled unambiguously in local wall time: the last hour of daylight time. In Eastern, that’s times of the form 5:MM UTC on the day daylight time ends. The local wall clock leaps from 1:59 (daylight time) back to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
astimezone()
mimics the local clock’s behavior by mapping two adjacent UTC hours into the same local hour then. In the Eastern example, UTC times of the form 5:MM and 6:MM both map to 1:MM when converted to Eastern, but earlier times have the
fold
attribute set to 0 and the later times have it set to 1. For example, at the Fall back transition of 2016, we get:
>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
... u = u0 + i*HOUR
... t = u.astimezone(Eastern)
... print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0
注意,
datetime
instances that differ only by the value of the
fold
attribute are considered equal in comparisons.
Applications that can’t bear wall-time ambiguities should explicitly check the value of the
fold
attribute or avoid using hybrid
tzinfo
subclasses; there are no ambiguities when using
timezone
, or any other fixed-offset
tzinfo
subclass (such as a class representing only EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).
另请参阅
-
zoneinfo
-
The
datetime
module has a basic
timezone
class (for handling arbitrary fixed offsets from UTC) and its
timezone.utc
attribute (a UTC
timezone
实例)。
zoneinfo
brings the
IANA time zone database
(also known as the Olson database) to Python, and its usage is recommended.
-
IANA time zone database
-
The Time Zone Database (often called tz, tzdata or zoneinfo) contains code and data that represent the history of local time for many representative locations around the globe. It is updated periodically to reflect changes made by political bodies to time zone boundaries, UTC offsets, and daylight-saving rules.