>>>
import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
... my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
使用 date 的例子:
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
datetime.date(2002, 3, 11)
>>> t = d.timetuple()
>>> for i in t:
... print(i)
2002 # year
3 # month
11 # day
0 # weekday (0 = Monday)
70 # 70th day in the year
>>> ic = d.isocalendar()
>>> for i in ic:
... print(i)
2002 # ISO year
11 # ISO week number
1 # ISO day number ( 1 = Monday )
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'
datetime 对象是一个包含了来自 date 对象和 time 对象所有信息的单一对象。 与 date 对象一样,datetime 假定当今的格列高利历向前后两个方向无限延伸;与 time 对象一样,datetime 假定每一天恰好有 3600*24 秒。
构造器 :
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
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 <= 日期 <= 给定年月对应的天数
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
如果参数不在这些范围内,则抛出 ValueError 异常。
其它构造器,所有的类方法:
classmethod datetime.today()
返回当前的本地 datetime,tzinfo 值为 None。 这等价于 datetime.fromtimestamp(time.time())。 另请参阅 now(), fromtimestamp()。
classmethod datetime.now(tz=None)
返回当前的本地 date 和 time。 如果可选参数 tz 为 None 或未指定,这就类似于 today(),但该方法会在可能的情况下提供比通过 time.time() 时间戳所获时间值更高的精度(例如,在提供了 C gettimeofday() 函数的平台上就可能做到)。
如果 tz 不为 None,它必须是 tzinfo 的子类的一个实例,并且当前日期和时间将转换为 tz 时区的日期和时间。 在这种情况下结果等价于 tz.fromutc(datetime.utcnow().replace(tzinfo=tz))。 另请参阅 today(), utcnow()。
classmethod datetime.fromtimestamp(timestamp, tz=None)
返回对应于 POSIX 时间戳例如 time.time() 的返回值的本地日期和时间。 如果可选参数 tz 为 None 或未指定,时间戳会被转换为所在平台的本地日期和时间,返回的 datetime 对象将为天真型。
如果 tz 不为 None,它必须是 tzinfo 子类的一个实例,并且时间戳将被转换到 tz 指定的时区。 在这种情况下结果等价于 tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))。
fromtimestamp() 可能引发 OverflowError,如果时间戳数值超出所在平台 C localtime() 或 gmtime() 函数的支持范围的话,并会在 localtime() 或 gmtime() 出错时引发 OSError。 通常该数值会被限制在 1970 年至 2038 年之间。 请注意在时间戳概念包含闰秒的非 POSIX 系统上,闰秒会被 fromtimestamp() 所忽略,结果可能导致两个相差一秒的时间戳产生相同的 datetime 对象。 另请参阅 utcfromtimestamp()。
3.3 版更變: 引发 OverflowError 而不是 ValueError,如果时间戳数值超出所在平台 C localtime() 或 gmtime() 函数的支持范围的话。 并会在 localtime() 或 gmtime() 出错时引发 OSError 而不是 ValueError。
classmethod datetime.utcfromtimestamp(timestamp)
返回对应于 POSIX 时间戳的 UTC datetime,其中 tzinfo 为 None。 这可能引发 OverflowError,如果时间戳数值超出所在平台 C gmtime() 函数的支持范围的话,并会在 gmtime() 出错时引发 OSError。 通常该数值并会限制在 1970 年至 2038 年之间。
要得到一个感知型 datetime
对象,应调用 fromtimestamp():
datetime.fromtimestamp(timestamp, timezone.utc)
在 POSIX 兼容的平台上,它等价于以下表达式:
datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
不同之处在于后一种形式总是支持完整年份范围:从 MINYEAR 到 MAXYEAR 的开区间。
3.3 版更變: 引发 OverflowError 而不是 ValueError,如果时间戳数值超出所在平台 C gmtime() 函数的支持范围的话。 并会在 gmtime() 出错时引发 OSError 而不是 ValueError。
classmethod datetime.combine(date, time)
Return a new datetime object whose date components are equal to the
given date object’s, and whose time components and tzinfo
attributes are equal to the given time object’s. For any
datetime object d,
d == datetime.combine(d.date(), d.timetz()). If date is a
datetime object, its time components and tzinfo attributes
are ignored.
classmethod datetime.strptime(date_string, format)
返回根据 format 解析与 date_string 相对应的 datetime,这等价于 datetime(*(time.strptime(date_string, format)[0:6])),如果 date_string 和 format 无法被 time.strptime() 解析或它返回一个不是时间元组的值,则将引发 ValueError。 要获取格式化指令的完整列表请参阅 strftime() 和 strptime() 的行为。
datetime.min
最早的可表示 datetime,datetime(MINYEAR, 1, 1, tzinfo=None)。
datetime2 是从中去掉的一段 timedelta 的结果,如果 timedelta.days > 0 则是在时间线上前进,如果 timedelta.days < 0 则后退。 结果具有与输入的 datetime 相同的 tzinfo 属性,并且操作完成后 datetime2 - datetime1 == timedelta。 如果 datetime2.year 将小于 MINYEAR 或大于 MAXYEAR 则会引发 OverflowError。 请注意即使输入的是一个感知型对象,该方法也不会进行时区调整。
Computes the datetime2 such that 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.
This isn’t quite equivalent to datetime1 + (-timedelta), because -timedelta
in isolation can overflow in cases where datetime1 - timedelta does not.
从一个 datetime 减去一个 datetime 仅对两个操作数均为简单型或均为感知型时有定义。 如果一个是感知型而另一个是简单型,则会引发 TypeError。
如果两个操作数都是简单型,或都是感知型且具有相同的 tzinfo 属性,tzinfo 属性会被忽略,结果是一个使得 datetime2 + t == datetime1 的 timedelta 对象 t。 在此情况下不会进行时区调整。
如果两个操作数都是感知型且具有不同的 tzinfo 属性,a-b 操作的行为就如同 a 和 b 被首先转换为简单型 UTC 日期时间。 结果将是 (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset()) 除非具体实现绝对不溢出。
当 datetime1 的时间在 datetime2 之前则认为 datetime1 小于 datetime2。
如果比较的一方是简单型而另一方是感知型,则如果尝试进行顺序比较将引发 TypeError。 对于相等比较,简单型实例将永远不等于感知型实例。
如果两个比较方都是感知型,且具有相同的 tzinfo 属性,相同的 tzinfo 属性会被忽略并对基本日期时间值进行比较。 如果两个比较方都是感知型且具有不同的 tzinfo 属性,两个比较方将首先通过减去它们的 UTC 差值(使用 self.utcoffset() 获取)来进行调整。
3.3 版更變: 简单型和感知型 datetime 实例之间的相等比较不会引发 TypeError。
为了防止比较操作回退为默认的对象地址比较方案,datetime 比较通常会引发 TypeError,如果比较目标不同样为 datetime 对象的话。 不过也可能会返回 NotImplemented 如果比较目标具有 timetuple() 属性的话。 这个钩子给予其他日期对象类型实现混合类型比较的机会。 否则,当 datetime 对象与不同类型的对象比较时将会引发 TypeError,除非 == 或 != 比较。 后两种情况将分别返回 False 或 True。
datetime 对象可以用作字典的键。 在布尔运算时,所有 datetime 对象都被视为真值。
实例方法:
datetime.date()
返回具有同样 year, month 和 day 值的 date 对象。
datetime.timetz()
Return time object with same hour, minute, second, microsecond, and
tzinfo attributes. See also method time().
datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
返回一个具有同样属性值的 datetime,除非通过任何关键字参数指定了某些属性值。 请注意可以通过指定 tzinfo=None 从一个感知型 datetime 创建一个简单型 datetime 而不必转换日期和时间值。
datetime.astimezone(tz=None)
返回一个具有新的 tzinfo 属性 tz 的 datetime 对象,并会调整日期和时间数据使得结果对应的 UTC 时间与 self 相同,但为 tz 时区的本地时间。
If provided, tz must be an instance of a tzinfo subclass, and its
utcoffset() and dst() methods must not return None. self must
be aware (self.tzinfo must not be None, and self.utcoffset() must
not return None).
If called without arguments (or with tz=None) the system local
timezone is assumed. 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.
If self.tzinfo is tz, self.astimezone(tz) is equal to self: no
adjustment of date or time data is performed. Else the result is local
time in time zone tz, representing the same UTC time as self: after
astz = dt.astimezone(tz), astz - astz.utcoffset() will usually have
the same date and time data as dt - dt.utcoffset(). The discussion
of class tzinfo explains the cases at Daylight Saving Time transition
boundaries where this cannot be achieved (an issue only if tz models both
standard and daylight time).
如果你只想附加一个时区对象 tz 给一个 datetime 对象 dt 而不调整日期和时间数据,请使用 dt.replace(tzinfo=tz)。 如果你只想从一个感知型 datetime 对象 dt 移除时区对象则不转换日期和时间数据,请使用 dt.replace(tzinfo=None)。
请注意默认的 tzinfo.fromutc() 方法在 tzinfo 的子类中可以被重载,从而影响 astimezone() 的返回结果。 如果忽略出错的情况,astimezone() 的行为就类似于:
def astimezone(self, tz):
if self.tzinfo is tz:
return self
# Convert self to UTC, and attach the new time zone object.
utc = (self - self.utcoffset()).replace(tzinfo=tz)
# Convert from UTC to tz's local time.
return tz.fromutc(utc)
3.3 版更變: tz 现在可以被省略。
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 representing a whole number of
minutes with magnitude less than one day.
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 representing a whole number of minutes
with magnitude less than one day.
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)),其中 yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 是日期在当前年份中的序号,起始序号 1 表示 1 月 1 日。 结果的 tm_isdst 旗标的设定会依据 dst() 方法:如果 tzinfo 为 None 或 dst() 返回 None,则 tm_isdst 将设为 -1;否则如果 dst() 返回一个非零值,则 tm_isdst 将设为 1;否则 tm_isdst 将设为 0。
datetime.utctimetuple()
如果 datetime 实例 d 为简单型,这类似于 d.timetuple(),不同之处为 tm_isdst 会强设为 0,无论 d.dst() 返回什么结果。 DST 对于 UTC 时间永远无效。
如果 d 为感知型,d 会通过减去 d.utcoffset() 被标准化为 UTC 时间,并返回标准化时间对应的 time.struct_time。 tm_isdst 会强设为 0。 请注意如果 d.year 为 MINYEAR 或 MAXYEAR 并且 UTC 调整超出一年的边界则可能引发 OverflowError。
datetime.timestamp()
返回对应于 datetime 实例的 POSIX 时间戳。 返回值是与 time.time() 类似的 float。
简单型 datetime 实例会假定为代表本地时间,并且此方法依赖于平台的 C mktime() 函数来执行转换。 由于在许多平台上 datetime 支持的值范围比 mktime() 更广,对于极其遥远的过去或末来时间此方法可能引发 OverflowError。
对于感知型 datetime 实例,返回值的计算方式为:
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
3.3 版新加入.
没有一个方法能直接从简单型 datetime 实例获取 POSIX 时间戳来代表 UTC 时间。 如果你的应用使用此惯例方式并且你的系统时区不是设为 UTC,你可以通过提供 tzinfo=timezone.utc 来获取 POSIX 时间戳:
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
或者通过直接计算时间戳:
timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
datetime.isoformat(sep='T')
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0,
YYYY-MM-DDTHH:MM:SS
If utcoffset() does not return None, a 6-character string is
appended, giving the UTC offset in (signed) hours and minutes:
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0
YYYY-MM-DDTHH:MM:SS+HH:MM
可选参数 sep (默认为 'T') 为单个分隔字符,会被放在结果的日期和时间两部分之间。例如
>>> 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'
datetime.__format__(format)
Same as datetime.strftime(). This makes it possible to specify a format
string for a datetime object when using str.format(). For a
complete list of formatting directives, see
strftime() 和 strptime() 的行为
.
使用 datetime 对象的例子:
>>> 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")
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.'
使用 datetime 并附带 tzinfo:
>>> from datetime import timedelta, datetime, tzinfo
>>> class GMT1(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=1) + self.dst(dt)
... def dst(self, dt):
... # DST starts last Sunday in March
... d = datetime(dt.year, 4, 1) # ends last Sunday in October
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=1)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +1"
>>> class GMT2(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=2) + self.dst(dt)
... def dst(self, dt):
... d = datetime(dt.year, 4, 1)
... self.dston = d - timedelta(days=d.weekday() + 1)
... d = datetime(dt.year, 11, 1)
... self.dstoff = d - timedelta(days=d.weekday() + 1)
... if self.dston <= dt.replace(tzinfo=None) < self.dstoff:
... return timedelta(hours=1)
... else:
... return timedelta(0)
... def tzname(self,dt):
... return "GMT +2"
>>> gmt1 = GMT1()
>>> # Daylight Saving Time
>>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
>>> dt1.dst()
datetime.timedelta(0)
>>> dt1.utcoffset()
datetime.timedelta(0, 3600)
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
>>> dt2.dst()
datetime.timedelta(0, 3600)
>>> dt2.utcoffset()
datetime.timedelta(0, 7200)
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(GMT2())
>>> dt3 # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2 # doctest: +ELLIPSIS
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
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.
如果给出一个此范围以外的参数,则会引发 ValueError。 所有参数值默认为 0,除了 tzinfo 默认为 None
。
time.min
早最的可表示 time, time(0, 0, 0, 0)。
time.resolution
两个不相等的 time 对象之间可能的最小间隔,timedelta(microseconds=1),但是请注意 time 对象并不支持算术运算。
实例属性(只读):
time.hour
取值范围是 range(24)。
支持的运算:
比较 time 和另一个 time,当 a 的时间在 b 之前时,则认为 a 小于 b。 如果比较的一方是简单型而另一方是感知型,则如果尝试进行顺序比较将引发 TypeError。 对于相等比较,简单型实例将永远不等于感知型实例。
如果两个比较方都是感知型,且具有相同的 tzinfo 属性,相同的 tzinfo 属性会被忽略并对基本时间值进行比较。 如果两个比较方都是感知型且具有不同的 tzinfo 属性,两个比较方将首先通过减去它们的 UTC 差值(使用 self.utcoffset() 获取)来进行调整。 为了防止将混合类型比较回退为基于对象地址的默认比较,当 time 对象与不同类型的对象比较时,将会引发 TypeError,除非比较运算符是 == 或 !=。 在后一种情况下将分别返回 False 或 True。
3.3 版更變: 简单型和感知型 time 实例之前的相等比较不会引发 TypeError。
哈希,以便用作字典的键
高效的封存
在布尔运算时,time 对象总是被视为真值。
3.5 版更變: 在 Python 3.5 之前,如果一个 time 对象代表 UTC 午夜零时则会被视为假值。 此行为被认为容易引发困惑和错误,因此从 Python 3.5 起已被去除。 详情参见 bpo-13936。
实例方法:
time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])
返回一个具有同样属性值的 time,除非通过任何关键字参数指定了某些属性值。 请注意可以通过指定 tzinfo=None 从一个感知型 time 创建一个简单型 time 而不必转换时间值。
time.isoformat()
Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
self.microsecond is 0, HH:MM:SS If utcoffset() does not return None, a
6-character string is appended, giving the UTC offset in (signed) hours and
minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
time.__format__(format)
Same as time.strftime(). This makes it possible to specify a format string
for a time object when using str.format(). For a
complete list of formatting directives, see
strftime() 和 strptime() 的行为.
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 representing a whole number of
minutes with magnitude less than one day.
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 representing a whole number of minutes
with magnitude less than one day.
time.tzname()
如果 tzinfo 为 None,则返回 None,否则返回 self.tzinfo.tzname(None),如果后者不返回 None 或者一个字符串对象则将引发异常。
>>> from datetime import time, tzinfo, timedelta
>>> class GMT1(tzinfo):
... def utcoffset(self, dt):
... return timedelta(hours=1)
... def dst(self, dt):
... return timedelta(0)
... def tzname(self,dt):
... return "Europe/Prague"
>>> t = time(12, 10, 30, tzinfo=GMT1())
>>> t # doctest: +ELLIPSIS
datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
>>> gmt = GMT1()
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'Europe/Prague'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 Europe/Prague'
>>> 'The {} is {:%H:%M}.'.format("time", t)
'The time is 12:10.'
class datetime.tzinfo
这是一个抽象基类,即这个类不可直接被实例化。 你必须从该类派生一个实体子类,并且(至少)提供你使用 datetime 需要的标准 tzinfo 方法的实现。 datetime 模块提供了 tzinfo 的一个简单实体子类,timezone,它能以与 UTC 的固定差值来表示不同的时区,例如 UTC 本身或北美的 EST 和 EDT。
tzinfo 的(某个实体子类)的实例可以被传给 datetime 和 time 对象的构造器。 这些对象会将它们的属性视为对应于本地时间,并且 tzinfo 对象支持展示本地时间与 UTC 的差值、时区名称以及 DST 差值的方法,都是与传给它们的日期或时间对象的相对值。
对于封存操作的特殊要求:一个 tzinfo 子类必须具有可不带参数调用的 __init__() 方法,否则它虽然可以被封存,但可能无法再次解封。 这是个技术性要求,在未来可能会被取消。
一个 tzinfo 的实体子类可能需要实现以下方法。 具体需要实现的方法取决于感知型 datetime 对象如何使用它。 如果有疑问,可以简单地全都实现。
tzinfo.utcoffset(dt)
Return offset of local time from UTC, in minutes east of UTC. If local time is
west of UTC, this should be negative. Note that this is intended to be 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 specifying a whole number of minutes in the range
-1439 to 1439 inclusive (1440 = 24*60; 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() 也不应返回 None。
默认的 utcoffset() 实现会引发 NotImplementedError。
tzinfo.dst(dt)
Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
None if DST information isn’t known. Return 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() calls dst() to account for
DST changes when crossing time zones.
一个可以同时处理标准时和夏令时的 tzinfo 子类的实例 tz 必须在此情形中保持一致:
tz.utcoffset(dt) - tz.dst(dt)
必须为具有同样的 tzinfo 子类实例 dt.tzinfo == tz 的每个 datetime 对象 dt 返回同样的结果,此表达式会产生时区的“标准时差”,它不应取决于具体日期或时间,只取决于地理位置。 datetime.astimezone() 的实现依赖此方法,但无法检测违反规则的情况;确保符合规则是程序员的责任。 如果一个 tzinfo 子类不能保证这一点,也许应该重载 tzinfo.fromutc() 的默认实现以便在任何情况下与 astimezone() 配合正常。
大多数 dst() 的实现可能会如以下两者之一:
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. Then
if dston <= dt.replace(tzinfo=None) < dstoff:
return timedelta(hours=1)
else:
return timedelta(0)
默认的 dst() 实现会引发 NotImplementedError。
tzinfo.tzname(dt)
将对应于 datetime 对象 dt 的时区名称作为字符串返回。 datetime 模块没有定义任何字符串名称相关内容,也不要求名称有任何特定含义。 例如,」GMT」, 「UTC」, 「-500」, 「-5:00」, 「EDT」, 「US/Eastern」, 「America/New York」 都是有效的返回值。 如果字符串名称未知则返回 None。 请注意这是一个方法而不是一个固定的字符串,这主要是因为某些 tzinfo 子类可能需要根据所传入的特定 dt 值返回不同的名称,特别是当 tzinfo 类要负责处理夏令时的时候。
默认的 tzname() 实现会引发 NotImplementedError。
这些方法会被 datetime 或 time 对象调用,用来对应它们的同名方法。 datetime 对象会将自身作为传入参数,而 time 对象会将 None 作为传入参数。 这样 tzinfo 子类的方法应当准备好接受 dt 参数值为 None 或是 datetime 类的实例。
当传入 None 时,应当由类的设计者来决定最佳回应方式。 例如,返回 None 适用于希望该类提示时间对象不参与 tzinfo 协议处理。 让 utcoffset(None) 返回标准 UTC 时差也许会更有用处,如果没有其他用于发现标准时差的约定。
当传入一个 datetime 对象来回应 datetime 方法时,dt.tzinfo 与 self 是同一对象。 tzinfo 方法可以依赖这一点,除非用户代码直接调用了 tzinfo 方法。 此行为的目的是使得 tzinfo 方法将 dt 解读为本地时间,而不需要担心其他时区的相关对象。
还有一个额外的 tzinfo 方法,某个子类可能会希望重载它:
tzinfo.fromutc(dt)
此方法会由默认的 datetime.astimezone() 实现来调用。 当被调用时,dt.tzinfo 为 self,并且 dt 的日期和时间数据会被视为代表 UTC 时间。 fromutc() 的目标是调整日期和时间数据,返回一个等价的 datetime 来表示 self 的本地时间。
大多数 tzinfo 子类应该能够毫无问题地继承默认的 fromutc() 实现。 它的健壮性足以处理固定差值的时区以及同时负责标准时和夏令时的时区,对于后者甚至还能处理 DST 转换时间在各个年份有变化的情况。 一个默认 fromutc() 实现可能无法在所有情况下正确处理的例子是(与 UTC 的)标准差值取决于所经过的特定日期和时间,这种情况可能由于政治原因而出现。 默认的 astimezone() 和 fromutc() 实现可能无法生成你希望的结果,如果这个结果恰好是跨越了标准差值发生改变的时刻当中的某个小时值的话。
忽略针对错误情况的代码,默认 fromutc() 实现的行为方式如下:
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
# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name
):
self.__offset = timedelta(minutes=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
# A class capturing the platform's idea of local time.
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 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
# http://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; 1am standard time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 1)
# 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; 1am standard 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, 1)
# 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;
# 1am standard 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
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
# Find start and end times for US DST. For years before 1967, return
# ZERO for no DST.
if 2006 < dt.year:
dststart, dstend = DSTSTART_2007, DSTEND_2007
elif 1986 < dt.year < 2007:
dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
elif 1966 < dt.year < 1987:
dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
else:
return ZERO
start = first_sunday_on_or_after(dststart.replace(year=dt.year))
end = first_sunday_on_or_after(dstend.replace(year=dt.year))
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
请注意同时负责标准时和夏令时的 tzinfo 子类在每年两次的 DST 转换点上会出现不可避免的微妙问题。 具体而言,考虑美国东部时区 (UTC -0500),它的 EDT 从三月的第二个星期天 1:59 (EST) 之后一分钟开始,并在十一月的第一个星期天 1:59 (EDT) 之后一分钟结束:
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. In order for astimezone() to make this guarantee, the
tzinfo.dst() method must consider times in the 「missing hour」 (2:MM for
Eastern) to be in daylight time.
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. In order for
astimezone() to make this guarantee, the tzinfo.dst() method must
consider times in the 「repeated hour」 to be in standard time. This is easily
arranged, as in the example, by expressing DST switch times in the time zone’s
standard local time.
Applications that can’t bear such ambiguities should 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)).
该标准库具有 timezone 类用来将相对于 UTC 和 timezone.utc 的任意固定差值处理为 UTC 时区实例。
pytz library brings the IANA timezone database (also known as the
Olson database) to Python and its usage is recommended.
IANA 时区数据库
The Time Zone Database (often called tz 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.
timezone 类是 tzinfo 的一个子类,它的每个实例代表一个由与 UTC 的固定差值所定义的时区。 请注意该类的对象不可被用于代表某些特殊地点的时区信息,例如在一年的不同日期使用不同差值,或是在历史上对民用时间进行过调整的地点。
class datetime.timezone(offset[,
name])
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) and represent a whole number of minutes,
otherwise ValueError is raised.
The name argument is optional. If specified it must be a string that
is used as the value returned by the tzname(dt) method. Otherwise,
tzname(dt) returns a string 『UTCsHH:MM』, where s is the sign of
offset, HH and MM are two digits of offset.hours and
offset.minutes respectively.
3.2 版新加入.
timezone.tzname(dt)
Return the fixed value specified when the timezone instance is
constructed or a string 『UTCsHH:MM』, where s is the sign of
offset, HH and MM are two digits of offset.hours and
offset.minutes respectively.
timezone.fromutc(dt)
返回 dt + offset。 dt 参数必须为一个感知型 datetime 实例,其中 tzinfo 值设为 self。
timezone.utc
UTC 时区,timezone(timedelta(0))。
8.1.8. strftime() 和 strptime() 的行为
date, datetime 和 time 对象都支持 strftime(format) 方法,可用来创建一个由指定格式字符串所控制的表示时间的字符串。 总体而言,d.strftime(fmt) 类似于 time 模块的 time.strftime(fmt, d.timetuple()) 但是并非所有对象都支持 timetuple() 方法。
Conversely, the datetime.strptime() class method creates a
datetime object from a string representing a date and time and a
corresponding format string. datetime.strptime(date_string, format) is
equivalent to datetime(*(time.strptime(date_string, format)[0:6])).
对于 time 对象,年、月、日的格式代码不应被使用,因为 time 对象没有这些值。 如果它们被使用,年份将被替换为 1900 而月和日将被替换为 1。
对于 date 对象,时、分、秒和微秒的格式代码不应被使用,因为 date 对象没有这些值。 如果它们被使用,它们都将被替换为 0。
对完整格式代码集的支持在不同平台上有所差异,因为 Python 要调用所在平台 C 库的 strftime() 函数,而不同平台的差异是很常见的。 要查看你所用平台所支持的完整格式代码集,请参阅 strftime(3) 文档。
以下列表显示了 C 标准(1989 版)所要求的全部格式代码,它们在带有标准 C 实现的所有平台上均可用。 请注意 1999 版 C 标准又添加了额外的格式代码。
由于此格式依赖于当前区域设置,因此对具体输出值应当保持谨慎预期。 字段顺序会发生改变(例如 「month/day/year」 与 「day/month/year」),并且输出可能包含使用区域设置所指定的默认编码格式的 Unicode 字符(例如如果当前区域为 ja_JP,则默认编码格式可能为 eucJP, SJIS 或 utf-8 中的一个;使用 locale.getlocale() 可确定当前区域设置的编码格式)。
strptime() 方法能够解析整个 [1, 9999] 范围内的年份,但 < 1000 的年份必须加零填充为 4 位数字宽度。
3.2 版更變: 在之前的版本中,strftime() 方法只限于 >= 1900 的年份。
3.3 版更變: 在版本3.2中,strftime() 方法只限于 years >= 1000。
当与 strptime() 方法一起使用时,如果使用 %I 指令来解析小时,%p 指令只影响输出小时字段。
与 time 模块不同的是, datetime 模块不支持闰秒。
当与 strptime() 方法一起使用时,%f 指令可接受一至六个数码及左边的零填充。 %f 是对 C 标准中格式字符集的扩展(但单独在 datetime 对象中实现,因此它总是可用)。
对于简单型对象,%z and %Z 格式代码会被替换为空字符串。
对于一个觉悟型对象而言:
utcoffset() is transformed into a 5-character string of the form
+HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
offset hours, and MM is a 2-digit string giving the number of UTC offset
minutes. For example, if utcoffset() returns
timedelta(hours=-3, minutes=-30), %z is replaced with the string
'-0330'.
如果 tzname() 返回 None,%Z 会被替换为一个空字符串。 在其他情况下 %Z 会被替换为返回值,这必须为一个字符串。
3.2 版更變: 当提供 %z 指令给 strptime() 方法时,将产生一个感知型 datetime 对象。 结果的 tzinfo 将被设为一个 timezone 实例。
When used with the strptime() method, %U and %W are only used
in calculations when the day of the week and the year are specified.
[1]就是说如果我们忽略相对论效应的话。