8.1. datetime — 基本的日期和时间类型¶
2.3 新版功能.
datetime 模块提供了可以通过多种方式操作日期和时间的类。在支持日期时间数学运算的同时,实现的关注点更着重于如何能够更有效地解析其属性用于格式化输出和数据操作。相关功能可以参阅 time 和 calendar 模块。
有两种日期和时间的对象:“简单型“和”感知型“。
感知型对象有着用足以支持一些应用层面算法和国家层面时间调整的信息,例如时区和夏令时,来让自己和其他的感知型对象区别开来。感知型对象是用来表达不对解释器开放的特定时间信息 1。
A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
For applications requiring aware objects, datetime and time
objects have an optional time zone information attribute, tzinfo, that
can be set to an instance of a subclass of the abstract tzinfo class.
These tzinfo objects capture information about the offset from UTC
time, the time zone name, and whether Daylight Saving Time is in effect. Note
that no concrete tzinfo classes are supplied by the datetime
module. Supporting timezones at whatever level of detail is required is up to
the application. The rules for time adjustment across the world are more
political than rational, and there is no standard suitable for every
application.
The datetime module exports the following constants:
8.1.1. 有效的类型¶
-
class
datetime.time 一个理想化的时间,它独立于任何特定的日期,假设每天一共有 24*60*60 秒(这里没有”闰秒”的概念)。 属性:
hour,minute,second,microsecond, 和tzinfo。
-
class
datetime.datetime 日期和时间的结合。属性:
year,month,day,hour,minute,second,microsecond, andtzinfo.
这些类型的对象都是不可变的。
date 类型的对象都是简单型的。
An object of type time or datetime may be naive or aware.
A datetime object d is aware if d.tzinfo is not None and
d.tzinfo.utcoffset(d) does not return None. If d.tzinfo is
None, or if d.tzinfo is not None but d.tzinfo.utcoffset(d)
returns None, d is naive. A time object t is aware
if t.tzinfo is not None and t.tzinfo.utcoffset(None) does not return
None. Otherwise, t is naive.
简单型和感知型之间的差别不适用于 timedelta 对象。
子类关系
object
timedelta
tzinfo
time
date
datetime
8.1.2. timedelta 类对象¶
timedelta 对象表示两个 date 或者 time 的时间间隔。
-
class
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶ All arguments are optional and default to
0. Arguments may be ints, longs, or floats, and may be positive or negative.只有 days,*seconds* 和 microseconds 会存储在内部,即python内部以 days,*seconds* 和 microseconds 三个单位作为存储的基本单位。参数单位转换规则如下:
1毫秒会转换成1000微秒。
1分钟会转换成60秒。
1小时会转换成3600秒。
1星期会转换成7天。
days, seconds, microseconds 本身也是标准化的,以保证表达方式的唯一性,例:
0 <= microseconds < 10000000 <= seconds < 3600*24(一天的秒数)-999999999 <= days <= 999999999
If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond. If no argument is a float, the conversion and normalization processes are exact (no information is lost).
如果标准化后的 days 数值超过了指定范围,将会抛出
OverflowError异常。需要注意的是,负数被标准化后的结果会让你大吃一惊。例如,
>>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999)
类属性:
-
timedelta.max¶ The most positive
timedeltaobject,timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
需要注意的是,因为标准化的缘故,timedelta.max > -timedelta.min,-timedelta.max 不可以表示一个 timedelta 类对象。
实例属性(只读):
属性 |
值 |
|---|---|
|
-999999999 至 999999999 ,含999999999 |
|
0 至 86399,包含86399 |
|
0 至 999999,包含999999 |
支持的运算:
运算 |
结果: |
|---|---|
|
t2 和 t3 的和。 运算后 t1-t2 == t3 and t1-t3 == t2 必为真值。(1) |
|
Difference of t2 and t3. Afterwards t1 == t2 - t3 and t2 == t1 + t3 are true. (1) |
|
Delta multiplied by an integer or long.
Afterwards t1 // i == t2 is true,
provided |
In general, t1 * i == t1 * (i-1) + t1 is true. (1) |
|
|
The floor is computed and the remainder (if any) is thrown away. (3) |
|
返回一个相同数值的 |
|
等价于 |
|
当 |
|
返回一个形如 |
|
Returns a string in the form
|
注释:
精确但可能会溢出。
精确且不会溢出。
除以0将会抛出异常
ZeroDivisionError。-timedelta.max 不是一个
timedelta类对象。String representations of
timedeltaobjects are normalized similarly to their internal representation. This leads to somewhat unusual results for negative timedeltas. For example:>>> timedelta(hours=-5) datetime.timedelta(-1, 68400) >>> print(_) -1 day, 19:00:00
除了上面列举的操作以外 timedelta 对象还支持与 date 和 datetime 对象进行特定的相加和相减运算(见下文)。
timedelta 对象与 timedelta 对象比较的支持是通过将表示较小时间差的 timedelta 对象视为较小值。 为了防止将混合类型比较回退为基于对象地址的默认比较,当 timedelta 对象与不同类型的对象比较时,将会引发 TypeError,除非比较运算符是 == 或 !=。 在后一种情况下将分别返回 False 或 True。
timedelta 对象是 hashable 类型的(可以作为字典关键字), 支持高效获取, 在布尔上下文中, timedelta 对象大多数情况下都被视为真,仅在不等于 timedelta(0) 时。
实例方法:
-
timedelta.total_seconds()¶ Return the total number of seconds contained in the duration. Equivalent to
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6computed with true division enabled.需要注意的是,时间间隔较大时,这个方法的结果中的微秒将会失真(大多数平台上大于270年视为一个较大的时间间隔)。
2.7 新版功能.
用法示例:
>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
... minutes=50, seconds=600) # adds up to 365 days
>>> year.total_seconds()
31536000.0
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(3285), 9)
>>> three_years = nine_years // 3;
>>> three_years, three_years.days // 365
(datetime.timedelta(1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True
8.1.3. date 对象¶
date 对象代表一个理想化历法中的日期(年、月和日),即当今的格列高利历向前后两个方向无限延伸。公元 1 年 1 月 1 日是第 1 日,公元 1 年 1 月 2 日是第 2 日, 依此类推。 这与 Dershowitz 与 Reingold 所著 Calendrical Calculations 中“预期格列高利”历法的定义一致,它是适用于该书中所有运算的基础历法。 请参阅该书了解在预期格列高利历序列与许多其他历法系统之间进行转换的算法。
-
class
datetime.date(year, month, day)¶ All arguments are required. Arguments may be ints or longs, in the following ranges:
MINYEAR <= year <= MAXYEAR1 <= month <= 121 <= 日期 <= 给定年月对应的天数
如果参数不在这些范围内,则抛出
ValueError异常。
其它构造器,所有的类方法:
-
classmethod
date.today()¶ 返回当地的当前日期。与``date.fromtimestamp(time.time())``等价。
-
classmethod
date.fromtimestamp(timestamp)¶ Return the local date corresponding to the POSIX timestamp, such as is returned by
time.time(). This may raiseValueError, if the timestamp is out of the range of values supported by the platform Clocaltime()function. It’s common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored byfromtimestamp().
-
classmethod
date.fromordinal(ordinal)¶ 返回对应于预期格列高利历序号的日期,其中公元 1 年 1 月 1 日的序号为 1。 除非
1 <= 序号 <= date.max.toordinal()否则会引发ValueError。 对于任意日期 d,date.fromordinal(d.toordinal()) == d。
类属性:
-
date.min¶ 最小的日期
date(MINYEAR, 1, 1)。
-
date.max¶ 最大的日期 ,
date(MAXYEAR, 12, 31)。
-
date.resolution¶ 两个日期对象的最小间隔,
timedelta(days=1)。
实例属性(只读):
-
date.month¶ 1 至 12(含)
-
date.day¶ 返回1到指定年月的天数间的数字。
支持的运算:
运算 |
结果: |
|---|---|
|
date2 等于从 date1 减去 |
|
计算 date2 的值使得 |
|
(3) |
|
如果 date1 的时间在 date2 之前则认为 date1 小于 date2 。 (4) |
注释:
如果
timedelta.days > 0则 date2 在时间线上前进,如果timedelta.days < 0则后退。 操作完成后date2 - date1 == timedelta.days。timedelta.seconds和timedelta.microseconds会被忽略。如果date2.year将小于MINYEAR或大于MAXYEAR则会引发OverflowError。.This isn’t quite equivalent to date1 + (-timedelta), because -timedelta in isolation can overflow in cases where date1 - timedelta does not.
timedelta.secondsandtimedelta.microsecondsare ignored.精确且不会溢出。 操作完成后 timedelta.seconds 和 timedelta.microseconds 均为0, 并且 date2 + timedelta == date1。
In other words,
date1 < date2if and only ifdate1.toordinal() < date2.toordinal(). In order to stop comparison from falling back to the default scheme of comparing object addresses, date comparison normally raisesTypeErrorif the other comparand isn’t also adateobject. However,NotImplementedis returned instead if the other comparand has atimetuple()attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when adateobject is compared to an object of a different type,TypeErroris raised unless the comparison is==or!=. The latter cases returnFalseorTrue, respectively.
日期可以作为字典的关键字。在布尔上下文中,所有的 date 对象都视为真。
实例方法:
-
date.replace(year, month, day)¶ 返回一个具有同样值的日期,除非通过任何关键字参数给出了某些形参的新值。 例如,如果
d == date(2002, 12, 31),则d.replace(day=26) == date(2002, 12, 26)。
-
date.timetuple()¶ 返回一个
time.struct_time,即与time.localtime()的返回类型相同。 hours, minutes 和 seconds 值为 0, 且 DST 标志值为 -1。d.timetuple()等价于time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)),其中yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1是日期在当前年份中的序号,起始序号1表示 1 月 1 日。
-
date.toordinal()¶ 返回日期的预期格列高利历序号,其中公元 1 年 1 月 1 日的序号为 1。 对于任意
date对象 d,date.fromordinal(d.toordinal()) == d。
-
date.weekday()¶ 返回一个整数代表星期几,星期一为0,星期天为6。例如,
date(2002, 12, 4).weekday() == 2,表示的是星期三。参阅isoweekday()。
-
date.isoweekday()¶ 返回一个整数代表星期几,星期一为1,星期天为7。例如:
date(2002, 12, 4).isoweekday() == 3,表示星期三。参见weekday(),isocalendar()。
-
date.isocalendar()¶ 返回一个三元元组,(ISO year, ISO week number, ISO weekday) 。
ISO日历是一个被广泛使用的公历。可以从 https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm 上查看更完整的说明。
ISO 年由 52 或 53 个完整星期构成,每个星期开始于星期一结束于星期日。 一个 ISO 年的第一个星期就是(格列高利)历法的的一年中第一个包含星期四的星期。 这被称为 1 号星期,其中星期四所在的 ISO 年与其所在的格列高利年相同。
例如,2004 年的第一天是一个星期四,因此 ISO 2004 年的第一个星期开始于 2003 年 12 月 29 日星期一,结束于 2004 年 1 月 4 日星期日,因此
date(2003, 12, 29).isocalendar() == (2004, 1, 1)anddate(2004, 1, 4).isocalendar() == (2004, 1, 7)。
-
date.isoformat()¶ 返回一个 ISO 8601 格式的字符串, ‘YYYY-MM-DD’。例如
date(2002, 12, 4).isoformat() == '2002-12-04'。
-
date.__str__()¶ 对于日期对象 d,
str(d)等价于d.isoformat()。
-
date.ctime()¶ 返回一个代表日期的字符串,例如
date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'。 在原生 Cctime()函数 (time.ctime()会发起调用该函数,但date.ctime()则不会) 遵循 C 标准的平台上,d.ctime()等价于time.ctime(time.mktime(d.timetuple()))。
-
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. For a complete list of formatting directives, see section strftime() 和 strptime() 的行为.
-
date.__format__(format)¶ Same as
date.strftime(). This makes it possible to specify a format string for adateobject when usingstr.format(). See section strftime() 和 strptime() 的行为.
计算距离特定事件天数的例子:
>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> 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
202
使用 date 的例子:
>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)
>>> t = d.timetuple()
>>> for i in t:
... print i
2002 # year
3 # month
11 # day
0
0
0
0 # weekday (0 = Monday)
70 # 70th day in the year
-1
>>> 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.'
8.1.4. datetime 对象¶
datetime 对象是一个包含了来自 date 对象和 time 对象所有信息的单一对象。 与 date 对象一样,datetime 假定当今的格列高利历向前后两个方向无限延伸;与 time 对象一样,datetime 假定每一天恰好有 3600*24 秒。
构造器 :
-
class
datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])¶ The year, month and day arguments are required. tzinfo may be
None, or an instance of atzinfosubclass. The remaining arguments may be ints or longs, in the following ranges:MINYEAR <= year <= MAXYEAR1 <= month <= 121 <= 日期 <= 给定年月对应的天数0 <= hour < 240 <= minute < 600 <= second < 600 <= microsecond < 1000000
如果参数不在这些范围内,则抛出
ValueError异常。
其它构造器,所有的类方法:
-
classmethod
datetime.today()¶ 返回当前的本地 datetime,
tzinfo值为None。 这等价于datetime.fromtimestamp(time.time())。 另请参阅now(),fromtimestamp()。
-
classmethod
datetime.now([tz])¶ 返回当前的本地 date 和 time。 如果可选参数 tz 为
None或未指定,这就类似于today(),但该方法会在可能的情况下提供比通过time.time()时间戳所获时间值更高的精度(例如,在提供了 Cgettimeofday()函数的平台上就可能做到)。如果 tz 不为
None,它必须是tzinfo的子类的一个实例,并且当前日期和时间将转换为 tz 时区的日期和时间。 在这种情况下结果等价于tz.fromutc(datetime.utcnow().replace(tzinfo=tz))。 另请参阅today(),utcnow()。
-
classmethod
datetime.utcnow()¶ Return the current UTC date and time, with
tzinfoNone. This is likenow(), but returns the current UTC date and time, as a naivedatetimeobject. See alsonow().
-
classmethod
datetime.fromtimestamp(timestamp[, tz])¶ 返回对应于 POSIX 时间戳例如
time.time()的返回值的本地日期和时间。 如果可选参数 tz 为None或未指定,时间戳会被转换为所在平台的本地日期和时间,返回的datetime对象将为天真型。如果 tz 不为
None,它必须是tzinfo子类的一个实例,并且时间戳将被转换到 tz 指定的时区。 在这种情况下结果等价于tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))。fromtimestamp()may raiseValueError, if the timestamp is out of the range of values supported by the platform Clocaltime()orgmtime()functions. 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 byfromtimestamp(), and then it’s possible to have two timestamps differing by a second that yield identicaldatetimeobjects. See alsoutcfromtimestamp().
-
classmethod
datetime.utcfromtimestamp(timestamp)¶ Return the UTC
datetimecorresponding to the POSIX timestamp, withtzinfoNone. This may raiseValueError, if the timestamp is out of the range of values supported by the platform Cgmtime()function. It’s common for this to be restricted to years in 1970 through 2038. See alsofromtimestamp().
-
classmethod
datetime.fromordinal(ordinal)¶ 返回对应于预期格列高利历序号的
datetime,其中公元 1 年 1 月 1 日的序号为 1。 除非1 <= ordinal <= datetime.max.toordinal()否则会引发ValueError。 结果的hour, minute, second 和 microsecond 值均为 0,并且tzinfo值为None。
-
classmethod
datetime.combine(date, time)¶ Return a new
datetimeobject whose date components are equal to the givendateobject’s, and whose time components andtzinfoattributes are equal to the giventimeobject’s. For anydatetimeobject d,d == datetime.combine(d.date(), d.timetz()). If date is adatetimeobject, its time components andtzinfoattributes are ignored.
-
classmethod
datetime.strptime(date_string, format)¶ Return a
datetimecorresponding to date_string, parsed according to format. This is equivalent todatetime(*(time.strptime(date_string, format)[0:6])).ValueErroris raised if the date_string and format can’t be parsed bytime.strptime()or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see section strftime() 和 strptime() 的行为.2.5 新版功能.
类属性:
实例属性(只读):
-
datetime.month¶ 1 至 12(含)
-
datetime.day¶ 返回1到指定年月的天数间的数字。
-
datetime.hour¶ 取值范围是
range(24)。
-
datetime.minute¶ 取值范围是
range(60)。
-
datetime.second¶ 取值范围是
range(60)。
-
datetime.microsecond¶ 取值范围是
range(1000000)。
支持的运算:
运算 |
结果: |
|---|---|
|
(1) |
|
(2) |
|
(3) |
|
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
tzinfoattribute 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。
If one comparand is naive and the other is aware,
TypeErroris raised. If both comparands are aware, and have the sametzinfoattribute, the commontzinfoattribute is ignored and the base datetimes are compared. If both comparands are aware and have differenttzinfoattributes, the comparands are first adjusted by subtracting their UTC offsets (obtained fromself.utcoffset()).
datetime 对象可以用作字典的键。 在布尔运算时,所有 datetime 对象都被视为真值。
实例方法:
-
datetime.time()¶ Return
timeobject with same hour, minute, second and microsecond.tzinfoisNone. See also methodtimetz().
-
datetime.timetz()¶ Return
timeobject with same hour, minute, second, microsecond, and tzinfo attributes. See also methodtime().
-
datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])¶ 返回一个具有同样属性值的 datetime,除非通过任何关键字参数指定了某些属性值。 请注意可以通过指定
tzinfo=None从一个感知型 datetime 创建一个简单型 datetime 而不必转换日期和时间值。
-
datetime.astimezone(tz)¶ 返回一个具有新的
tzinfo属性 tz 的datetime对象,并会调整日期和时间数据使得结果对应的 UTC 时间与 self 相同,但为 tz 时区的本地时间。tz must be an instance of a
tzinfosubclass, and itsutcoffset()anddst()methods must not returnNone. self must be aware (self.tzinfomust not beNone, andself.utcoffset()must not returnNone).If
self.tzinfois 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: afterastz = dt.astimezone(tz),astz - astz.utcoffset()will usually have the same date and time data asdt - dt.utcoffset(). The discussion of classtzinfoexplains 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)
-
datetime.utcoffset()¶ If
tzinfoisNone, returnsNone, else returnsself.tzinfo.utcoffset(self), and raises an exception if the latter doesn’t returnNone, or atimedeltaobject representing a whole number of minutes with magnitude less than one day.
-
datetime.dst()¶ If
tzinfoisNone, returnsNone, else returnsself.tzinfo.dst(self), and raises an exception if the latter doesn’t returnNone, or atimedeltaobject representing a whole number of minutes with magnitude less than one day.
-
datetime.tzname()¶ 如果
tzinfo为None,则返回None,否则返回self.tzinfo.tzname(self),如果后者不返回None或者一个字符串对象则将引发异常。
-
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 时间永远无效。If d is aware, d is normalized to UTC time, by subtracting
d.utcoffset(), and atime.struct_timefor the normalized time is returned.tm_isdstis forced to 0. Note that the result’stm_yearmember may beMINYEAR-1 orMAXYEAR+1, if d.year wasMINYEARorMAXYEARand UTC adjustment spills over a year boundary.
-
datetime.toordinal()¶ 返回日期的预期格列高利历序号。 与
self.date().toordinal()相同。
-
datetime.weekday()¶ 返回一个整数代表星期几,星期一为 0,星期天为 6。 相当于
self.date().weekday()。 另请参阅isoweekday()。
-
datetime.isoweekday()¶ 返回一个整数代表星期几,星期一为 1,星期天为 7。 相当于
self.date().isoweekday()。 另请参阅weekday(),isocalendar()。
-
datetime.isocalendar()¶ 返回一个 3 元组 (ISO 年份, ISO 周序号, ISO 周日期)。 相当于
self.date().isocalendar()。
-
datetime.isoformat([sep])¶ Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if
microsecondis 0, YYYY-MM-DDTHH:MM:SSIf
utcoffset()does not returnNone, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, ifmicrosecondis 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.ctime()¶ 返回一个代表日期和时间的字符串,例如
datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'。 在原生 Cctime()函数 (time.ctime()会发起调用该函数,但datetime.ctime()则不会) 遵循 C 标准的平台上,d.ctime()等价于time.ctime(time.mktime(d.timetuple()))。
-
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 section strftime() 和 strptime() 的行为.
-
datetime.__format__(format)¶ Same as
datetime.strftime(). This makes it possible to specify a format string for adatetimeobject when usingstr.format(). See section 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")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
... print it
...
2006 # year
11 # month
21 # day
16 # hour
30 # minute
0 # second
1 # weekday (0 = Monday)
325 # number of days since 1st January
-1 # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
... print it
...
2006 # ISO year
47 # ISO week
2 # ISO weekday
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'
使用 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
datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
>>> dt2.utctimetuple() == dt3.utctimetuple()
True
8.1.5. time 对象¶
一个 time 对象代表某个日期内的(本地)时间,它独立于任何特定日期,并可通过 tzinfo 对象来调整。
-
class
datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])¶ All arguments are optional. tzinfo may be
None, or an instance of atzinfosubclass. The remaining arguments may be ints or longs, in the following ranges:0 <= hour < 240 <= minute < 600 <= second < 600 <= microsecond < 1000000.
如果给出一个此范围以外的参数,则会引发
ValueError。 所有参数值默认为0,除了 tzinfo 默认为None。
类属性:
实例属性(只读):
-
time.hour¶ 取值范围是
range(24)。
-
time.minute¶ 取值范围是
range(60)。
-
time.second¶ 取值范围是
range(60)。
-
time.microsecond¶ 取值范围是
range(1000000)。
支持的运算:
comparison of
timetotime, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware,TypeErroris raised. If both comparands are aware, and have the sametzinfoattribute, the commontzinfoattribute is ignored and the base times are compared. If both comparands are aware and have differenttzinfoattributes, the comparands are first adjusted by subtracting their UTC offsets (obtained fromself.utcoffset()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when atimeobject is compared to an object of a different type,TypeErroris raised unless the comparison is==or!=. The latter cases returnFalseorTrue, respectively.哈希,以便用作字典的键
高效的封存
in Boolean contexts, a
timeobject is considered to be true if and only if, after converting it to minutes and subtractingutcoffset()(or0if that’sNone), the result is non-zero.
实例方法:
-
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 returnNone, 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.__str__()¶ 对于时间对象 t,
str(t)等价于t.isoformat()。
-
time.strftime(format)¶ Return a string representing the time, controlled by an explicit format string. For a complete list of formatting directives, see section strftime() 和 strptime() 的行为.
-
time.__format__(format)¶ Same as
time.strftime(). This makes it possible to specify a format string for atimeobject when usingstr.format(). See section strftime() 和 strptime() 的行为.
-
time.utcoffset()¶ If
tzinfoisNone, returnsNone, else returnsself.tzinfo.utcoffset(None), and raises an exception if the latter doesn’t returnNoneor atimedeltaobject representing a whole number of minutes with magnitude less than one day.
-
time.dst()¶ If
tzinfoisNone, returnsNone, else returnsself.tzinfo.dst(None), and raises an exception if the latter doesn’t returnNone, or atimedeltaobject 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
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.'
8.1.6. tzinfo 对象¶
-
class
datetime.tzinfo¶ This is an abstract base class, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard
tzinfomethods needed by thedatetimemethods you use. Thedatetimemodule does not supply any concrete subclasses oftzinfo.tzinfo的(某个实体子类)的实例可以被传给datetime和time对象的构造器。 这些对象会将它们的属性视为对应于本地时间,并且tzinfo对象支持展示本地时间与 UTC 的差值、时区名称以及 DST 差值的方法,都是与传给它们的日期或时间对象的相对值。对于封存操作的特殊要求:一个
tzinfo子类必须具有可不带参数调用的__init__()方法,否则它虽然可以被封存,但可能无法再次解封。 这是个技术性要求,在未来可能会被取消。一个
tzinfo的实体子类可能需要实现以下方法。 具体需要实现的方法取决于感知型datetime对象如何使用它。 如果有疑问,可以简单地全都实现。
-
tzinfo.utcoffset(self, 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
tzinfoobject represents both time zone and DST adjustments,utcoffset()should return their sum. If the UTC offset isn’t known, returnNone. Else the value returned must be atimedeltaobject 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 ofutcoffset()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(self, dt)¶ Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
Noneif DST information isn’t known. Returntimedelta(0)if DST is not in effect. If DST is in effect, return the offset as atimedeltaobject (seeutcoffset()for details). Note that DST offset, if applicable, has already been added to the UTC offset returned byutcoffset(), so there’s no need to consultdst()unless you’re interested in obtaining DST info separately. For example,datetime.timetuple()calls itstzinfoattribute’sdst()method to determine how thetm_isdstflag should be set, andtzinfo.fromutc()callsdst()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(self, 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(self, 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
Example tzinfo classes:
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
# 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
rzinfo.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 UTC, 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)).
参见
- pytz
The standard library has no
tzinfoinstances, but there exists a third-party library which brings the IANA timezone database (also known as the Olson database) to Python: pytz.pytz contains up-to-date information 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.
8.1.7. strftime() 和 strptime() 的行为¶
date, datetime 和 time 对象都支持 strftime(format) 方法,可用来创建一个由指定格式字符串所控制的表示时间的字符串。 总体而言,d.strftime(fmt) 类似于 time 模块的 time.strftime(fmt, d.timetuple()) 但是并非所有对象都支持 timetuple() 方法。
相反地,datetime.strptime() 类方法可根据一个表示时间的字符串和对应的格式字符串创建来一个 datetime 对象。 datetime.strptime(date_string, format) 等价于 datetime(*(time.strptime(date_string, format)[0:6])),差别在于当 format 包含小于秒的部分或者时区差值信息的时候,这些信息被 datetime.strptime 所支持但会被 time.strptime 所丢弃。
对于 time 对象,年、月、日的格式代码不应被使用,因为 time 对象没有这些值。 如果它们被使用,年份将被替换为 1900 而月和日将被替换为 1。
对于 date 对象,时、分、秒和微秒的格式代码不应被使用,因为 date 对象没有这些值。 如果它们被使用,它们都将被替换为 0。
对完整格式代码集的支持在不同平台上有所差异,因为 Python 要调用所在平台 C 库的 strftime() 函数,而不同平台的差异是很常见的。 要查看你所用平台所支持的完整格式代码集,请参阅 strftime(3) 文档。
出于相同的原因,对于包含当前区域设置字符集所无法表示的 Unicode 码位的格式字符串的处理方式也取决于具体平台。 在某些平台上这样的码位会不加修改地原样输出,而在其他平台上 strftime 则可能引发 UnicodeError 或只返回一个空字符串。
以下列表显示了 C 标准(1989 版)所要求的全部格式代码,它们在带有标准 C 实现的所有平台上均可用。 请注意 1999 版 C 标准又添加了额外的格式代码。
The exact range of years for which strftime() works also varies across
platforms. Regardless of platform, years before 1900 cannot be used.
指令 |
含义 |
示例 |
注释 |
|---|---|---|---|
|
当地工作日的缩写。 |
Sun, Mon, …, Sat (美国);
So, Mo, …, Sa (德国)
|
(1) |
|
当地工作日的全名。 |
Sunday, Monday, …, Saturday (美国);
Sonntag, Montag, …, Samstag (德国)
|
(1) |
|
以十进制数显示的工作日,其中0表示星期日,6表示星期六。 |
0, 1, …, 6 |
|
|
补零后,以十进制数显示的月份中的一天。 |
01, 02, …, 31 |
|
|
当地月份的缩写。 |
Jan, Feb, …, Dec (美国);
Jan, Feb, …, Dez (德国)
|
(1) |
|
当地月份的全名。 |
January, February, …, December (美国);
Januar, Februar, …, Dezember (德国)
|
(1) |
|
补零后,以十进制数显示的月份。 |
01, 02, …, 12 |
|
|
补零后,以十进制数表示的,不带世纪的年份。 |
00, 01, …, 99 |
|
|
十进制数表示的带世纪的年份。 |
1970, 1988, 2001, 2013 |
|
|
以补零后的十进制数表示的小时(24 小时制)。 |
00, 01, …, 23 |
|
|
以补零后的十进制数表示的小时(12 小时制)。 |
01, 02, …, 12 |
|
|
本地化的 AM 或 PM 。 |
AM, PM (美国);
am, pm (德国)
|
(1), (2) |
|
补零后,以十进制数显示的分钟。 |
00, 01, …, 59 |
|
|
补零后,以十进制数显示的秒。 |
00, 01, …, 59 |
(3) |
|
以十进制数表示的微秒,在左侧补零。 |
000000, 000001, …, 999999 |
(4) |
|
UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). |
(empty), +0000, -0400, +1030 |
(5) |
|
时区名称(如果对象为简单型则为空字符串)。 |
(空), UTC, EST, CST |
|
|
以补零后的十进制数表示的一年中的日序号。 |
001, 002, …, 366 |
|
|
以补零后的十进制数表示的一年中的周序号(星期日作为每周的第一天)。 在新的一年中第一个星期日之前的所有日子都被视为是在第 0 周。 |
00, 01, …, 53 |
(6) |
|
以十进制数表示的一年中的周序号(星期一作为每周的第一天)。 在新的一年中第一个第期一之前的所有日子都被视为是在第 0 周。 |
00, 01, …, 53 |
(6) |
|
本地化的适当日期和时间表示。 |
Tue Aug 16 21:30:00 1988 (美国);
Di 16 Aug 21:30:00 1988 (德国)
|
(1) |
|
本地化的适当日期表示。 |
08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
|
(1) |
|
本地化的适当时间表示。 |
21:30:00 (en_US);
21:30:00 (de_DE)
|
(1) |
|
字面的 |
% |
注释:
由于此格式依赖于当前区域设置,因此对具体输出值应当保持谨慎预期。 字段顺序会发生改变(例如 “month/day/year” 与 “day/month/year”),并且输出可能包含使用区域设置所指定的默认编码格式的 Unicode 字符(例如如果当前区域为
ja_JP,则默认编码格式可能为eucJP,SJIS或utf-8中的一个;使用locale.getlocale()可确定当前区域设置的编码格式)。当与
strptime()方法一起使用时,如果使用%I指令来解析小时,%p指令只影响输出小时字段。%fis an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with thestrptime()method, the%fdirective accepts from one to six digits and zero pads on the right.2.6 新版功能.
对于简单型对象,
%zand%Z格式代码会被替换为空字符串。对于一个觉悟型对象而言:
%zutcoffset()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, ifutcoffset()returnstimedelta(hours=-3, minutes=-30),%zis replaced with the string'-0330'.%Z如果
tzname()返回None,%Z会被替换为一个空字符串。 在其他情况下%Z会被替换为返回值,这必须为一个字符串。
When used with the
strptime()method,%Uand%Ware only used in calculations when the day of the week and the year are specified.
备注
- 1
就是说如果我们忽略相对论效应的话。
