8.1. datetime

版本 2.3 新增。

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. 虽然支持日期和时间的运算,该实现的焦点是为输出格式化和操作高效地提取属性。相关的功能,请参阅 timecalendar 模块。

有两种日期和时间类型:“naive” 和 “aware”。

An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, to locate itself relative to other aware objects. aware 对象用于表示时间的一个特定的时刻,它是明确无二的[1]

naive 对象没有充分的信息来明确地相对其他日期/时间定位它自己。一个 naive 对象表示的是世界协调时(UTC)、本地时间还是其它时区的时间完全取决于程序,就像一个特定的数字表示的是米、英里还是质量一样。

对于需要 aware 对象的应用程序,datetimetime 对象有一个可选的时区信息属性tzinfo,可以设置成抽象类 tzinfo 的子类的实例。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:

datetime.MINYEAR

date 对象或者 datetime 对象允许的最小年份。MINYEAR is 1.

datetime.MAXYEAR

date 或者 datetime 对象允许的最大年份。MAXYEAR is 9999.

See also

Module calendar
General calendar related functions.
Module time
Time access and conversions.

8.1.1. Available Types

class datetime.date

理想化的 naive 日期,假设当前的公历曾经并永远生效。属性:yearmonthday

class datetime.time

An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds (there is no notion of “leap seconds” here). 属性:hourminutesecondmicrosecondtzinfo

class datetime.datetime

日期和时间的组合。属性:yearmonthdayhourminutesecondmicrosecondtzinfo

class datetime.timedelta

两个datetime或者datetime实例之间的时间差值,精度为微秒。

class datetime.tzinfo

时区信息对象的抽象基类。datetimetime 类使用它来提供一个定制化的时间调节(例如,表示时区和/或夏令时)。

这些类型的对象是不可变的。

date 类型的对象永远是 naive 的。

timedatetime 类型的对象既可能是 naive 的也可能是 aware 的。datetime的对象d 是Aware的如果d.tzinfo 不为None 并且d.tzinfo.utcoffset(d) 不会返回None如果 d.tzinfoNone,或者d.tzinfo 不为None 但是d.tzinfo.utcoffset(d) 返回None,那么d 是Naive。time 对象t 是Aware的如果t.tzinfo 不为 Nonet.tzinfo.utcoffset(None) 不会返回None否则,t 是Naive 的。

naive 和 aware 之间的区别,不适用于 timedelta 对象。

子类之间的关系:

object
    timedelta
    tzinfo
    time
    date
        datetime

8.1.2. timedelta

timedelta 对象表示一个时间段,即两个日期 (date) 或时间 (datetime) 之间的差。

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

所有的参数都是可选的且默认为0参数可以是整数、长整数或者浮点数,也可以是正数或者负数。

内部只存储dayssecondsmicroseconds 所有的参数都将转换成这三个单位:

  • A millisecond is converted to 1000 microseconds.
  • A minute is converted to 60 seconds.
  • An hour is converted to 3600 seconds.
  • A week is converted to 7 days.

然后标准化days、seconds 和microseconds 使得它们的表示是唯一的:

  • 0 <= microseconds < 1000000
  • 0 <= seconds < 3600*24 (the number of seconds in one day)
  • -999999999 <= days <= 999999999

如果任一参数为浮点数且有小数形式的microseconds,那么会将所有参数剩下的微秒小数部分相加并将它们的和舍入到最接近的微秒。如果没有参数是浮点数,那么转换和标准化过程是精确的(没有损失信息)。

如果标准化之后的days值落入指定的范围之外,则抛出OverflowError

注意负数值的标准化起初可能让人吃惊。例如,

>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)

类属性有:

timedelta.min

最小的负的timedelta 对象,为timedelta(-999999999)

timedelta.max

最大的正的timedelta 对象,为timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)

timedelta.resolution

两个不相等的timedelta 对象之间可能的最小差值,为timedelta(microseconds=1)

注意,由于标准化的缘故,timedelta.max > -timedelta.mintimedelta对象不能够表示-timedelta.max

实例属性(只读):

Attribute Value
days Between -999999999 and 999999999 inclusive
seconds Between 0 and 86399 inclusive
microseconds Between 0 and 999999 inclusive

支持的操作:

Operation Result
t1 = t2 + t3 Sum of t2 and t3. Afterwards t1-t2 == t3 and t1-t3 == t2 are true. (1)
t1 = t2 - t3 Difference of t2 and t3. Afterwards t1 == t2 - t3 and t2 == t1 + t3 are true. (1)
t1 = t2 * i or t1 = i * t2 Delta multiplied by an integer or long. Afterwards t1 // i == t2 is true, provided i != 0.
  In general, t1 * i == t1 * (i-1) + t1 is true. (1)
t1 = t2 // i The floor is computed and the remainder (if any) is thrown away. (3)
+t1 Returns a timedelta object with the same value. (2)
-t1 equivalent to timedelta(-t1.days, -t1.seconds, -t1.microseconds), and to t1* -1. (1)(4)
abs(t) equivalent to +t when t.days >= 0, and to -t when t.days < 0. (2)
str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)
repr(t) Returns a string in the form datetime.timedelta(D[, S[, U]]), where D is negative for negative t. (5)

注意:

  1. 计算是精确的,但是可能出现溢出。

  2. 计算是精确的,且不会出现溢出。

  3. 除0将抛出ZeroDivisionError

  4. timedelta 对象不能够表示-timedelta.max

  5. timedelta 对象的字符串表示被标准化成它们内部表示类似的形式。这导致负的timedeltas 的结果有些不寻常。例如:

    >>> timedelta(hours=-5)
    datetime.timedelta(-1, 68400)
    >>> print(_)
    -1 day, 19:00:00
    

除了上面列出来的操作,timedelta 对象还支持与datedatetime 对象的加法和减法(见下文)。

timedelta 对象支持比较操作,表示较小的时间差的timedelta 被认为是小的那个timedelta。为了阻止混合比较最后变成默认的比较对象的地址,当timedelta 对象与不同类型的对象比较时,将抛出TypeError 除非比较用的是== 或者!=后两个情况分别返回FalseTrue

timedelta 对象是可哈希的 (用作字典的键),支持高效的pickling,并且在布尔环境下, timedelta 对象被认为是真只要它不等于timedelta(0)

实例方法:

timedelta.total_seconds()

返回时间差中包含的总的秒数。等同于(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6在启用真除法时的计算值。

注意,对于非常巨大的时间差(在大多数平台上是大于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 对象表示理想化日历中的日期(年、月和日),即当前的公历可以在两个方向无限扩展。第一年的一月一日叫做第一天,第一年的一月二日叫做第二天,以此类推。这符合Dershowitz 和Reingold 的《历法计算》一书中关于公历的定义,它是所有历法计算的基础。公历和其它许多历法系统的转换可以参阅此书。

class datetime.date(year, month, day)

所有的参数都是必须的。参数可以是整数或者长整数,范围如下:

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

如果给出的是超出范围之外的参数,将抛出ValueError

其它构造函数,都是类方法:

classmethod date.today()

返回当前本地的日期。等同于date.fromtimestamp(time.time())

classmethod date.fromtimestamp(timestamp)

返回对应POSIX timestamp 的本地日期,POSIX timestamp 就是time.time()返回的那种。如果timestamp 超出平台C 函数localtime() 支持的范围,将抛出ValueError通常限制年份在1970 到 2038之间。注意在闰秒的非POSIX 系统上,虽然它们的时间戳概念中包括闰秒,但是闰秒将被fromtimestamp()忽略。

classmethod date.fromordinal(ordinal)

返回对应于公历序数的日期,其中第一年的一月一日为序数1。除非1 <= ordinal <= date.max.toordinal(),否则将抛出ValueError对于任何日期ddate.fromordinal(d.toordinal()) == d.

类属性:

date.min

可以表示的最早的日期,为date(MINYEAR, 1, 1)

date.max

可以表示的最晚的日期,为date(MAXYEAR, 12, 31)

date.resolution

两个不相等的日期对象之间可能的最小差值,为timedelta(days=1)

实例属性(只读):

date.year

MINYEARMAXYEAR 之间,包括这两个值。

date.month

在 1 到 12 之间,包括 1 和 12。

date.day

在 1 到给出的年份和月份之间的天数。

支持的操作:

Operation Result
date2 = date1 + timedelta date2 is timedelta.days days removed from date1. (1)
date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1. (2)
timedelta = date1 - date2 (3)
date1 < date2 date1 is considered less than date2 when date1 precedes date2 in time. (4)

注意:

  1. date2 is moved forward in time if timedelta.days > 0, or backward if timedelta.days < 0. Afterward date2 - date1 == timedelta.days. timedelta.seconds and timedelta.microseconds are ignored. OverflowError is raised if date2.year would be smaller than MINYEAR or larger than MAXYEAR.
  2. This isn’t quite equivalent to date1 + (-timedelta), because -timedelta in isolation can overflow in cases where date1 - timedelta does not. timedelta.seconds and timedelta.microseconds are ignored.
  3. This is exact, and cannot overflow. timedelta.seconds and timedelta.microseconds are 0, and date2 + timedelta == date1 after.
  4. In other words, date1 < date2 if and only if date1.toordinal() < date2.toordinal(). In order to stop comparison from falling back to the default scheme of comparing object addresses, date comparison normally raises TypeError if the other comparand isn’t also a date object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a date object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, 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()返回的一样。小时、分钟和秒数为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 天以来的天数。

date.toordinal()

返回公历日期的序数,其中第1年的1月1日为第1天。对于任何 date 对象ddate.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()

返回一个3元组, (ISO year, ISO week number, ISO weekday)。

The ISO calendar is a widely used variant of the Gregorian calendar. See http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for a good explanation.

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

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

date.isoformat()

返回以ISO 8601 格式‘YYYY-MM-DD’表示日期的字符串。例如,date(2002, 12, 4).isoformat() == '2002-12-04'

date.__str__()

对于日期dstr(d)等同于d.isoformat()

date.ctime()

返回一个表示日期的字符串,例如date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'在原生的ctime() 函数(time.ctime() 调用的函数,而不是date.ctime() 调用的函数)遵循C 标准的平台上d.ctime() 等同于time.ctime(time.mktime(d.timetuple()))

date.strftime(format)

返回一个表示日期的字符串,由显式的格式字符串控制。引用小时、分钟和秒的格式代码的值将为0。完整的格式指令列表,请参阅strftime() and strptime() Behavior一节。

date.__format__(format)

等同于date.strftime()这使得在使用 str.format()时可以为date 对象指定格式字符串。 参见strftime() and strptime() Behavior一节。

计算离一个事件还有多少天的例子:

>>> 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 秒。

Constructor:

class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

year, month 和 day 参数是必须的。tzinfo 可以是 None,或者 tzinfo 子类的实例。The remaining arguments may be ints or longs, 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

如果给出的参数超出这些范围,则抛出 ValueError 异常。

其它的构造器,它们都是类方法:

classmethod datetime.today()

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

classmethod datetime.now([tz])

Return the current local date and time. 如果可选的参数 tzNone 或者没有指定,就如同today(),但是,如果可能, 提供比time.time() 时间戳更高的精度(例如,在提供C 函数gettimeofday() 的平台上,这是可能的)。

Else tz must be an instance of a class tzinfo subclass, and the current date and time are converted to tz‘s time zone. In this case the result is equivalent to tz.fromutc(datetime.utcnow().replace(tzinfo=tz)). See also today(), utcnow().

classmethod datetime.utcnow()

返回当前 UTC 日期和时间,其 tzinfoNone它就像 now(),但返回的是 UTC 日期和时间,为 naive 的 datetime 对象。另请参阅 now()

classmethod datetime.fromtimestamp(timestamp[, tz])

返回与POSIX timestamp对应的本地日期和时间,POSIX timestamp例如time.time()返回的值。如果可选参数tzNone或没有指定,timestamp被转换成平台的本地日期和时间,返回的datetime对象是naive的。

否则tz必须是类tzinfo的一个子类,timestamp被转换成tz的时区。这种情况下,结果等同于tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))

fromtimestamp()可能会引发ValueError,如果timestamp超出平台的C函数localtime()gmtime()支持的值的范围。常见的做法是现在年份在1970和2038之间。注意,在timestamp中包含闰秒的非POSIX系统上,闰秒被fromtimestamp()忽略,所以两个具有不同秒数的timestamps有可能生成相同的datetime对象。另请参阅utcfromtimestamp()

classmethod datetime.utcfromtimestamp(timestamp)

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

classmethod datetime.fromordinal(ordinal)

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

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)

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

New in version 2.5.

Class attributes:

datetime.min

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

datetime.max

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

datetime.resolution

不相等的 datetime 对象之间可能的最小差值,timedelta(microseconds=1)

Instance attributes (read-only):

datetime.year

MINYEARMAXYEAR 之间,包括这两个值。

datetime.month

在 1 到 12 之间,包括 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 argument to the datetime constructor, or None if none was passed.

Supported operations:

Operation Result
datetime2 = datetime1 + timedelta (1)
datetime2 = datetime1 - timedelta (2)
timedelta = datetime1 - datetime2 (3)
datetime1 < datetime2 Compares datetime to datetime. (4)
  1. 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 is raised if datetime2.year would be smaller than MINYEAR or larger than MAXYEAR. Note that no time zone adjustments are done even if the input is an aware object.

  2. 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.

  3. Subtraction of a datetime from a datetime is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, TypeError is raised.

    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 object t such that 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 first. The result is (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset()) except that the implementation never overflows.

  4. datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time.

    If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is ignored and the base datetimes 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()).

    注意

    In order to stop comparison from falling back to the default scheme of comparing object addresses, datetime comparison normally raises TypeError if the other comparand isn’t also a datetime object. However, NotImplemented is returned instead if the other comparand has a timetuple() attribute. This hook gives other kinds of date objects a chance at implementing mixed-type comparison. If not, when a datetime object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.

datetime objects can be used as dictionary keys. 在布尔语境中,所有的 datetime 对象都为真。

Instance methods:

datetime.date()

返回具有相同年、月、日的 date 对象。

datetime.time()

返回具有相同时、分、秒和微秒的 time 对象。tzinfoNone另请参阅 timetz() 方法。

datetime.timetz()

返回具有相同时、分、秒、微秒和时区属性的 time 对象。另请参阅 time() 方法。

datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])

返回具有相同属性的 datetime,但通过任何关键字参数指定新值的那些属性除外。 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.astimezone(tz)

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

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 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).

If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use dt.replace(tzinfo=tz). If you merely want to remove the time zone 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(). 忽略错误的情况下,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 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.tzname()

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

datetime.timetuple()

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

datetime.utctimetuple()

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

If d is aware, d is normalized to UTC time, by subtracting d.utcoffset(), and a time.struct_time for the normalized time is returned. tm_isdst is forced to 0. Note that the result’s tm_year member may be MINYEAR-1 or MAXYEAR+1, if d.year was MINYEAR or MAXYEAR and UTC adjustment spills over a year boundary.

datetime.toordinal()

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

datetime.weekday()

返回一个整数,表示星期几;其中星期一为 0,星期日为 6。等同于 self.date().weekday()另请参阅 isoweekday()

datetime.isoweekday()

返回一个整数,表示星期几;其中星期一为 1,星期日为 7。 等同于 self.date().isoweekday()另请参阅 weekday(), isocalendar()

datetime.isocalendar()

Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as 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 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

The optional argument sep (default '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):
...     def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
datetime.__str__()

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

datetime.ctime()

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

datetime.strftime(format)

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

datetime.__format__(format)

Same as datetime.strftime(). This makes it possible to specify format string for a datetime object when using str.format(). See section strftime() and strptime() Behavior.

Examples of working with datetime objects:

>>> from datetime import datetime, date, time
>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using datetime.now() or datetime.utcnow()
>>> datetime.now()   
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
>>> datetime.utcnow()   
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:   
...     print it
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:   
...     print it
...
2006    # ISO year
47      # ISO week
2       # ISO weekday
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'

Using datetime with tzinfo:

>>> 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

时间对象表示一天,独立于任何特定的一天,并通过 tzinfo对象调整的(本地)的时间。

class datetime.time([hour[, minute[, second[, microsecond[, tzinfo]]]]])

所有参数都是可选项。tzinfo 可以为 None,或者是 tzinfo实例的子类。参数可以是整型或者长整型,参数范围如下:

  • 0 <= hour < 24
  • 0 <= minute < 60
  • 0 <= second < 60
  • 0 <= microsecond < 1000000.

如果参数超出所给范围, 会导致一个ValueError异常。除了tzinfo之外,所有参数默认值是0, tzinfo的默认值是None.

Class attributes:

time.min

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

time.max

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

time.resolution

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

Instance attributes (read-only):

time.hour

In range(24).

time.minute

In range(60).

time.second

In range(60).

time.microsecond

In range(1000000).

time.tzinfo

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

Supported operations:

  • comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised. If both comparands are aware, and have the same tzinfo attribute, the common tzinfo attribute is 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()). In order to stop mixed-type comparisons from falling back to the default comparison by object address, when a time object is compared to an object of a different type, TypeError is raised unless the comparison is == or !=. The latter cases return False or True, respectively.
  • hash, use as dict key
  • efficient pickling
  • in Boolean contexts, a time object is considered to be true if and only if, after converting it to minutes and subtracting utcoffset() (or 0 if that’s None), the result is non-zero.

Instance methods:

time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])

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

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.__str__()

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

time.strftime(format)

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

time.__format__(format)

Same as time.strftime(). This makes it possible to specify format string for a time object when using str.format(). See section strftime() and strptime() Behavior.

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()

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

例子:

>>> from datetime import time, tzinfo
>>> 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

tzinfo 是一个抽象的基类,也就是说,不应该直接实例化这个类。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 module does not supply any concrete subclasses of tzinfo.

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.

如果要对该对象pickling, 有个要求: tzinfo 的子类的 __init__() 方法不接受其他参数,否则的话,只能 pickle,不能 unpickle。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(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 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

If utcoffset() does not return None, dst() should not return None either.

The default implementation of utcoffset() raises NotImplementedError.

tzinfo.dst(self, 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.

An instance tz of a 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)

or

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)

The default implementation of dst() raises NotImplementedError.

tzinfo.tzname(self, dt)

Return the time zone name corresponding to the datetime object 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.

The default implementation of tzname() raises 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 argument of None, or of class datetime.

When 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.

When a datetime object is passed in response to a datetime method, 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 timezones.

There is one more tzinfo method that a subclass may wish to override:

tzinfo.fromutc(self, dt)

This is called from the default datetime.astimezone() implementation. When called from that, dt.tzinfo is self, and 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

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")

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. 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)).

See also

pytz

The standard library has no tzinfo instances, 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 timezone database
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()

datedatetimetime对象都支持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]))

对于time对象,不应该使用年、月、日的格式码,因为time对象没有这样的值。如果非要使用它们,则年用1900代替,月和日用1代替。

对于date对象,不应该使用时、分、秒和微秒的格式码,因为date对象没有这样的值。如果非要使用它们,则它们都用0代替。

平台支持的完整格式码集是各不相同的,因为Python调用平台C库的strftime()函数,而平台的差异是很常见的。若要查看你的平台上支持的完整格式码集,请参阅strftime(3)的文档。

下面列出了C标准(1989版)要求的所有格式码,它们在所有具有标准C实现的平台上都可以工作。注意1999版的C标准添加了额外的格式码。

strftime()能工作的准确年份范围在各个平台之间也是各不相同。无论哪个平台,1900之前的年份都是不可以使用的。

指令 含义 例子 备注
%a 星期名称的区域性简写。
Sun, Mon, ..., Sat (en_US);
So, Mo, ..., Sa (de_DE)
(1)
%A 星期名称的区域性全称。
Sunday, Monday, ..., Saturday (en_US);
Sonntag, Montag, ..., Samstag (de_DE)
(1)
%w 数字形式的星期,0表示星期日,6表示星期六。 0, 1, ..., 6  
%d 以0填充的十进制数字表示的月份中的日期。 01, 02, ..., 31  
%b 月份名称的区域性简写。
Jan, Feb, ..., Dec (en_US);
Jan, Feb, ..., Dez (de_DE)
(1)
%B 月份名称的区域性全称。
January, February, ..., December (en_US);
Januar, Februar, ..., Dezember (de_DE)
(1)
%m 以0填充的十进制数表示的月份。 01, 02, ..., 12  
%y 以0填充的十进制数表示的不带世纪的年份。 00, 01, ..., 99  
%Y 以0填充的十进制数表示的带有世纪的年份。 1970, 1988, 2001, 2013  
%H 以0填充的十进制数表示的小时(24小时制)。 00, 01, ..., 23  
%I 以0填充的十进制数表示的小时(12小时制)。 01, 02, ..., 12  
%p AM或PM区域性设置。
AM, PM (en_US);
am, pm (de_DE)
(1), (2)
%M 以0填充的十进制数表示的分钟。 00, 01, ..., 59  
%S 以0填充的十进制数表示的秒数。 00, 01, ..., 59 (3)
%f 十进制数表示的微秒,左边以0填充。 000000, 000001, ..., 999999 (4)
%z +HHMM或-HHMM形式的UTC offset(如果对象是naive的,则为空字符串)。 (empty), +0000, -0400, +1030 (5)
%Z 时区名称(如果对象是naive的,则为空字符串)。 (empty), UTC, EST, CST  
%j 以0填充的十进制数字表示的一年中的日期。 001, 002, ..., 366  
%U 以0填充的十进制数字表示的一年中的第几个星期(星期天作为一个星期的第一天)。新的一年中第一个星期天之前的所有日期都被认为是在第0个星期。 00, 01, ..., 53 (6)
%W 以0填充的十进制数字表示的一年中的第几个星期(星期一作为一个星期的第一天)。 新的一年中第一个星期一之前的所有日期都被认为是在第0个星期。 00, 01, ..., 53 (6)
%c 适合区域设置的日期和时间表示。
Tue Aug 16 21:30:00 1988 (en_US);
Di 16 Aug 21:30:00 1988 (de_DE)
(1)
%x 适合区域的日期表示。
08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
(1)
%X 适合区域的时间表示。
21:30:00 (en_US);
21:30:00 (de_DE)
(1)
%% '%'字符的字面值。 %  

备注:

  1. Because the format depends on the current locale, care should be taken when making assumptions about the output value. Field orderings will vary (for example, “month/day/year” versus “day/month/year”), and the output may contain Unicode characters encoded using the locale’s default encoding (for example, if the current locale is ja_JP, the default encoding could be any one of eucJP, SJIS, or utf-8; use locale.getlocale() to determine the current locale’s encoding).

  2. When used with the strptime() method, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

  3. Unlike the time module, the datetime module does not support leap seconds.

  4. %f is 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 the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.

    New in version 2.6.

  5. For a naive object, the %z and %Z format codes are replaced by empty strings.

    For an aware object:

    %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'.

    %Z

    If tzname() returns None, %Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string.

  6. 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.

Footnotes

[1]If, that is, we ignore the effects of Relativity