You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

589 lines
19 KiB

4 years ago
  1. pytz - World Timezone Definitions for Python
  2. ============================================
  3. :Author: Stuart Bishop <stuart@stuartbishop.net>
  4. Introduction
  5. ~~~~~~~~~~~~
  6. pytz brings the Olson tz database into Python. This library allows
  7. accurate and cross platform timezone calculations using Python 2.4
  8. or higher. It also solves the issue of ambiguous times at the end
  9. of daylight saving time, which you can read more about in the Python
  10. Library Reference (``datetime.tzinfo``).
  11. Almost all of the Olson timezones are supported.
  12. .. note::
  13. This library differs from the documented Python API for
  14. tzinfo implementations; if you want to create local wallclock
  15. times you need to use the ``localize()`` method documented in this
  16. document. In addition, if you perform date arithmetic on local
  17. times that cross DST boundaries, the result may be in an incorrect
  18. timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get
  19. 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A
  20. ``normalize()`` method is provided to correct this. Unfortunately these
  21. issues cannot be resolved without modifying the Python datetime
  22. implementation (see PEP-431).
  23. Installation
  24. ~~~~~~~~~~~~
  25. This package can either be installed from a .egg file using setuptools,
  26. or from the tarball using the standard Python distutils.
  27. If you are installing from a tarball, run the following command as an
  28. administrative user::
  29. python setup.py install
  30. If you are installing using setuptools, you don't even need to download
  31. anything as the latest version will be downloaded for you
  32. from the Python package index::
  33. easy_install --upgrade pytz
  34. If you already have the .egg file, you can use that too::
  35. easy_install pytz-2008g-py2.6.egg
  36. Example & Usage
  37. ~~~~~~~~~~~~~~~
  38. Localized times and date arithmetic
  39. -----------------------------------
  40. >>> from datetime import datetime, timedelta
  41. >>> from pytz import timezone
  42. >>> import pytz
  43. >>> utc = pytz.utc
  44. >>> utc.zone
  45. 'UTC'
  46. >>> eastern = timezone('US/Eastern')
  47. >>> eastern.zone
  48. 'US/Eastern'
  49. >>> amsterdam = timezone('Europe/Amsterdam')
  50. >>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
  51. This library only supports two ways of building a localized time. The
  52. first is to use the ``localize()`` method provided by the pytz library.
  53. This is used to localize a naive datetime (datetime with no timezone
  54. information):
  55. >>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
  56. >>> print(loc_dt.strftime(fmt))
  57. 2002-10-27 06:00:00 EST-0500
  58. The second way of building a localized time is by converting an existing
  59. localized time using the standard ``astimezone()`` method:
  60. >>> ams_dt = loc_dt.astimezone(amsterdam)
  61. >>> ams_dt.strftime(fmt)
  62. '2002-10-27 12:00:00 CET+0100'
  63. Unfortunately using the tzinfo argument of the standard datetime
  64. constructors ''does not work'' with pytz for many timezones.
  65. >>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt) # /!\ Does not work this way!
  66. '2002-10-27 12:00:00 LMT+0020'
  67. It is safe for timezones without daylight saving transitions though, such
  68. as UTC:
  69. >>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt) # /!\ Not recommended except for UTC
  70. '2002-10-27 12:00:00 UTC+0000'
  71. The preferred way of dealing with times is to always work in UTC,
  72. converting to localtime only when generating output to be read
  73. by humans.
  74. >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
  75. >>> loc_dt = utc_dt.astimezone(eastern)
  76. >>> loc_dt.strftime(fmt)
  77. '2002-10-27 01:00:00 EST-0500'
  78. This library also allows you to do date arithmetic using local
  79. times, although it is more complicated than working in UTC as you
  80. need to use the ``normalize()`` method to handle daylight saving time
  81. and other timezone transitions. In this example, ``loc_dt`` is set
  82. to the instant when daylight saving time ends in the US/Eastern
  83. timezone.
  84. >>> before = loc_dt - timedelta(minutes=10)
  85. >>> before.strftime(fmt)
  86. '2002-10-27 00:50:00 EST-0500'
  87. >>> eastern.normalize(before).strftime(fmt)
  88. '2002-10-27 01:50:00 EDT-0400'
  89. >>> after = eastern.normalize(before + timedelta(minutes=20))
  90. >>> after.strftime(fmt)
  91. '2002-10-27 01:10:00 EST-0500'
  92. Creating local times is also tricky, and the reason why working with
  93. local times is not recommended. Unfortunately, you cannot just pass
  94. a ``tzinfo`` argument when constructing a datetime (see the next
  95. section for more details)
  96. >>> dt = datetime(2002, 10, 27, 1, 30, 0)
  97. >>> dt1 = eastern.localize(dt, is_dst=True)
  98. >>> dt1.strftime(fmt)
  99. '2002-10-27 01:30:00 EDT-0400'
  100. >>> dt2 = eastern.localize(dt, is_dst=False)
  101. >>> dt2.strftime(fmt)
  102. '2002-10-27 01:30:00 EST-0500'
  103. Converting between timezones is more easily done, using the
  104. standard astimezone method.
  105. >>> utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899))
  106. >>> utc_dt.strftime(fmt)
  107. '2006-03-26 21:34:59 UTC+0000'
  108. >>> au_tz = timezone('Australia/Sydney')
  109. >>> au_dt = utc_dt.astimezone(au_tz)
  110. >>> au_dt.strftime(fmt)
  111. '2006-03-27 08:34:59 AEDT+1100'
  112. >>> utc_dt2 = au_dt.astimezone(utc)
  113. >>> utc_dt2.strftime(fmt)
  114. '2006-03-26 21:34:59 UTC+0000'
  115. >>> utc_dt == utc_dt2
  116. True
  117. You can take shortcuts when dealing with the UTC side of timezone
  118. conversions. ``normalize()`` and ``localize()`` are not really
  119. necessary when there are no daylight saving time transitions to
  120. deal with.
  121. >>> utc_dt = datetime.utcfromtimestamp(1143408899).replace(tzinfo=utc)
  122. >>> utc_dt.strftime(fmt)
  123. '2006-03-26 21:34:59 UTC+0000'
  124. >>> au_tz = timezone('Australia/Sydney')
  125. >>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
  126. >>> au_dt.strftime(fmt)
  127. '2006-03-27 08:34:59 AEDT+1100'
  128. >>> utc_dt2 = au_dt.astimezone(utc)
  129. >>> utc_dt2.strftime(fmt)
  130. '2006-03-26 21:34:59 UTC+0000'
  131. ``tzinfo`` API
  132. --------------
  133. The ``tzinfo`` instances returned by the ``timezone()`` function have
  134. been extended to cope with ambiguous times by adding an ``is_dst``
  135. parameter to the ``utcoffset()``, ``dst()`` && ``tzname()`` methods.
  136. >>> tz = timezone('America/St_Johns')
  137. >>> normal = datetime(2009, 9, 1)
  138. >>> ambiguous = datetime(2009, 10, 31, 23, 30)
  139. The ``is_dst`` parameter is ignored for most timestamps. It is only used
  140. during DST transition ambiguous periods to resolve that ambiguity.
  141. >>> tz.utcoffset(normal, is_dst=True)
  142. datetime.timedelta(-1, 77400)
  143. >>> tz.dst(normal, is_dst=True)
  144. datetime.timedelta(0, 3600)
  145. >>> tz.tzname(normal, is_dst=True)
  146. 'NDT'
  147. >>> tz.utcoffset(ambiguous, is_dst=True)
  148. datetime.timedelta(-1, 77400)
  149. >>> tz.dst(ambiguous, is_dst=True)
  150. datetime.timedelta(0, 3600)
  151. >>> tz.tzname(ambiguous, is_dst=True)
  152. 'NDT'
  153. >>> tz.utcoffset(normal, is_dst=False)
  154. datetime.timedelta(-1, 77400)
  155. >>> tz.dst(normal, is_dst=False)
  156. datetime.timedelta(0, 3600)
  157. >>> tz.tzname(normal, is_dst=False)
  158. 'NDT'
  159. >>> tz.utcoffset(ambiguous, is_dst=False)
  160. datetime.timedelta(-1, 73800)
  161. >>> tz.dst(ambiguous, is_dst=False)
  162. datetime.timedelta(0)
  163. >>> tz.tzname(ambiguous, is_dst=False)
  164. 'NST'
  165. If ``is_dst`` is not specified, ambiguous timestamps will raise
  166. an ``pytz.exceptions.AmbiguousTimeError`` exception.
  167. >>> tz.utcoffset(normal)
  168. datetime.timedelta(-1, 77400)
  169. >>> tz.dst(normal)
  170. datetime.timedelta(0, 3600)
  171. >>> tz.tzname(normal)
  172. 'NDT'
  173. >>> import pytz.exceptions
  174. >>> try:
  175. ... tz.utcoffset(ambiguous)
  176. ... except pytz.exceptions.AmbiguousTimeError:
  177. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  178. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  179. >>> try:
  180. ... tz.dst(ambiguous)
  181. ... except pytz.exceptions.AmbiguousTimeError:
  182. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  183. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  184. >>> try:
  185. ... tz.tzname(ambiguous)
  186. ... except pytz.exceptions.AmbiguousTimeError:
  187. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  188. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  189. Problems with Localtime
  190. ~~~~~~~~~~~~~~~~~~~~~~~
  191. The major problem we have to deal with is that certain datetimes
  192. may occur twice in a year. For example, in the US/Eastern timezone
  193. on the last Sunday morning in October, the following sequence
  194. happens:
  195. - 01:00 EDT occurs
  196. - 1 hour later, instead of 2:00am the clock is turned back 1 hour
  197. and 01:00 happens again (this time 01:00 EST)
  198. In fact, every instant between 01:00 and 02:00 occurs twice. This means
  199. that if you try and create a time in the 'US/Eastern' timezone
  200. the standard datetime syntax, there is no way to specify if you meant
  201. before of after the end-of-daylight-saving-time transition. Using the
  202. pytz custom syntax, the best you can do is make an educated guess:
  203. >>> loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 30, 00))
  204. >>> loc_dt.strftime(fmt)
  205. '2002-10-27 01:30:00 EST-0500'
  206. As you can see, the system has chosen one for you and there is a 50%
  207. chance of it being out by one hour. For some applications, this does
  208. not matter. However, if you are trying to schedule meetings with people
  209. in different timezones or analyze log files it is not acceptable.
  210. The best and simplest solution is to stick with using UTC. The pytz
  211. package encourages using UTC for internal timezone representation by
  212. including a special UTC implementation based on the standard Python
  213. reference implementation in the Python documentation.
  214. The UTC timezone unpickles to be the same instance, and pickles to a
  215. smaller size than other pytz tzinfo instances. The UTC implementation
  216. can be obtained as pytz.utc, pytz.UTC, or pytz.timezone('UTC').
  217. >>> import pickle, pytz
  218. >>> dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
  219. >>> naive = dt.replace(tzinfo=None)
  220. >>> p = pickle.dumps(dt, 1)
  221. >>> naive_p = pickle.dumps(naive, 1)
  222. >>> len(p) - len(naive_p)
  223. 17
  224. >>> new = pickle.loads(p)
  225. >>> new == dt
  226. True
  227. >>> new is dt
  228. False
  229. >>> new.tzinfo is dt.tzinfo
  230. True
  231. >>> pytz.utc is pytz.UTC is pytz.timezone('UTC')
  232. True
  233. Note that some other timezones are commonly thought of as the same (GMT,
  234. Greenwich, Universal, etc.). The definition of UTC is distinct from these
  235. other timezones, and they are not equivalent. For this reason, they will
  236. not compare the same in Python.
  237. >>> utc == pytz.timezone('GMT')
  238. False
  239. See the section `What is UTC`_, below.
  240. If you insist on working with local times, this library provides a
  241. facility for constructing them unambiguously:
  242. >>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
  243. >>> est_dt = eastern.localize(loc_dt, is_dst=True)
  244. >>> edt_dt = eastern.localize(loc_dt, is_dst=False)
  245. >>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))
  246. 2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500
  247. If you pass None as the is_dst flag to localize(), pytz will refuse to
  248. guess and raise exceptions if you try to build ambiguous or non-existent
  249. times.
  250. For example, 1:30am on 27th Oct 2002 happened twice in the US/Eastern
  251. timezone when the clocks where put back at the end of Daylight Saving
  252. Time:
  253. >>> dt = datetime(2002, 10, 27, 1, 30, 00)
  254. >>> try:
  255. ... eastern.localize(dt, is_dst=None)
  256. ... except pytz.exceptions.AmbiguousTimeError:
  257. ... print('pytz.exceptions.AmbiguousTimeError: %s' % dt)
  258. pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00
  259. Similarly, 2:30am on 7th April 2002 never happened at all in the
  260. US/Eastern timezone, as the clocks where put forward at 2:00am skipping
  261. the entire hour:
  262. >>> dt = datetime(2002, 4, 7, 2, 30, 00)
  263. >>> try:
  264. ... eastern.localize(dt, is_dst=None)
  265. ... except pytz.exceptions.NonExistentTimeError:
  266. ... print('pytz.exceptions.NonExistentTimeError: %s' % dt)
  267. pytz.exceptions.NonExistentTimeError: 2002-04-07 02:30:00
  268. Both of these exceptions share a common base class to make error handling
  269. easier:
  270. >>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError)
  271. True
  272. >>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError)
  273. True
  274. A special case is where countries change their timezone definitions
  275. with no daylight savings time switch. For example, in 1915 Warsaw
  276. switched from Warsaw time to Central European time with no daylight savings
  277. transition. So at the stroke of midnight on August 5th 1915 the clocks
  278. were wound back 24 minutes creating an ambiguous time period that cannot
  279. be specified without referring to the timezone abbreviation or the
  280. actual UTC offset. In this case midnight happened twice, neither time
  281. during a daylight saving time period. pytz handles this transition by
  282. treating the ambiguous period before the switch as daylight savings
  283. time, and the ambiguous period after as standard time.
  284. >>> warsaw = pytz.timezone('Europe/Warsaw')
  285. >>> amb_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=True)
  286. >>> amb_dt1.strftime(fmt)
  287. '1915-08-04 23:59:59 WMT+0124'
  288. >>> amb_dt2 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)
  289. >>> amb_dt2.strftime(fmt)
  290. '1915-08-04 23:59:59 CET+0100'
  291. >>> switch_dt = warsaw.localize(datetime(1915, 8, 5, 00, 00, 00), is_dst=False)
  292. >>> switch_dt.strftime(fmt)
  293. '1915-08-05 00:00:00 CET+0100'
  294. >>> str(switch_dt - amb_dt1)
  295. '0:24:01'
  296. >>> str(switch_dt - amb_dt2)
  297. '0:00:01'
  298. The best way of creating a time during an ambiguous time period is
  299. by converting from another timezone such as UTC:
  300. >>> utc_dt = datetime(1915, 8, 4, 22, 36, tzinfo=pytz.utc)
  301. >>> utc_dt.astimezone(warsaw).strftime(fmt)
  302. '1915-08-04 23:36:00 CET+0100'
  303. The standard Python way of handling all these ambiguities is not to
  304. handle them, such as demonstrated in this example using the US/Eastern
  305. timezone definition from the Python documentation (Note that this
  306. implementation only works for dates between 1987 and 2006 - it is
  307. included for tests only!):
  308. >>> from pytz.reference import Eastern # pytz.reference only for tests
  309. >>> dt = datetime(2002, 10, 27, 0, 30, tzinfo=Eastern)
  310. >>> str(dt)
  311. '2002-10-27 00:30:00-04:00'
  312. >>> str(dt + timedelta(hours=1))
  313. '2002-10-27 01:30:00-05:00'
  314. >>> str(dt + timedelta(hours=2))
  315. '2002-10-27 02:30:00-05:00'
  316. >>> str(dt + timedelta(hours=3))
  317. '2002-10-27 03:30:00-05:00'
  318. Notice the first two results? At first glance you might think they are
  319. correct, but taking the UTC offset into account you find that they are
  320. actually two hours appart instead of the 1 hour we asked for.
  321. >>> from pytz.reference import UTC # pytz.reference only for tests
  322. >>> str(dt.astimezone(UTC))
  323. '2002-10-27 04:30:00+00:00'
  324. >>> str((dt + timedelta(hours=1)).astimezone(UTC))
  325. '2002-10-27 06:30:00+00:00'
  326. Country Information
  327. ~~~~~~~~~~~~~~~~~~~
  328. A mechanism is provided to access the timezones commonly in use
  329. for a particular country, looked up using the ISO 3166 country code.
  330. It returns a list of strings that can be used to retrieve the relevant
  331. tzinfo instance using ``pytz.timezone()``:
  332. >>> print(' '.join(pytz.country_timezones['nz']))
  333. Pacific/Auckland Pacific/Chatham
  334. The Olson database comes with a ISO 3166 country code to English country
  335. name mapping that pytz exposes as a dictionary:
  336. >>> print(pytz.country_names['nz'])
  337. New Zealand
  338. What is UTC
  339. ~~~~~~~~~~~
  340. 'UTC' is `Coordinated Universal Time`_. It is a successor to, but distinct
  341. from, Greenwich Mean Time (GMT) and the various definitions of Universal
  342. Time. UTC is now the worldwide standard for regulating clocks and time
  343. measurement.
  344. All other timezones are defined relative to UTC, and include offsets like
  345. UTC+0800 - hours to add or subtract from UTC to derive the local time. No
  346. daylight saving time occurs in UTC, making it a useful timezone to perform
  347. date arithmetic without worrying about the confusion and ambiguities caused
  348. by daylight saving time transitions, your country changing its timezone, or
  349. mobile computers that roam through multiple timezones.
  350. .. _Coordinated Universal Time: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
  351. Helpers
  352. ~~~~~~~
  353. There are two lists of timezones provided.
  354. ``all_timezones`` is the exhaustive list of the timezone names that can
  355. be used.
  356. >>> from pytz import all_timezones
  357. >>> len(all_timezones) >= 500
  358. True
  359. >>> 'Etc/Greenwich' in all_timezones
  360. True
  361. ``common_timezones`` is a list of useful, current timezones. It doesn't
  362. contain deprecated zones or historical zones, except for a few I've
  363. deemed in common usage, such as US/Eastern (open a bug report if you
  364. think other timezones are deserving of being included here). It is also
  365. a sequence of strings.
  366. >>> from pytz import common_timezones
  367. >>> len(common_timezones) < len(all_timezones)
  368. True
  369. >>> 'Etc/Greenwich' in common_timezones
  370. False
  371. >>> 'Australia/Melbourne' in common_timezones
  372. True
  373. >>> 'US/Eastern' in common_timezones
  374. True
  375. >>> 'Canada/Eastern' in common_timezones
  376. True
  377. >>> 'Australia/Yancowinna' in all_timezones
  378. True
  379. >>> 'Australia/Yancowinna' in common_timezones
  380. False
  381. Both ``common_timezones`` and ``all_timezones`` are alphabetically
  382. sorted:
  383. >>> common_timezones_dupe = common_timezones[:]
  384. >>> common_timezones_dupe.sort()
  385. >>> common_timezones == common_timezones_dupe
  386. True
  387. >>> all_timezones_dupe = all_timezones[:]
  388. >>> all_timezones_dupe.sort()
  389. >>> all_timezones == all_timezones_dupe
  390. True
  391. ``all_timezones`` and ``common_timezones`` are also available as sets.
  392. >>> from pytz import all_timezones_set, common_timezones_set
  393. >>> 'US/Eastern' in all_timezones_set
  394. True
  395. >>> 'US/Eastern' in common_timezones_set
  396. True
  397. >>> 'Australia/Victoria' in common_timezones_set
  398. False
  399. You can also retrieve lists of timezones used by particular countries
  400. using the ``country_timezones()`` function. It requires an ISO-3166
  401. two letter country code.
  402. >>> from pytz import country_timezones
  403. >>> print(' '.join(country_timezones('ch')))
  404. Europe/Zurich
  405. >>> print(' '.join(country_timezones('CH')))
  406. Europe/Zurich
  407. Internationalization - i18n/l10n
  408. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  409. Pytz is an interface to the IANA database, which uses ASCII names. The `Unicode Consortium's Unicode Locales (CLDR) <http://cldr.unicode.org>`_
  410. project provides translations. Thomas Khyn's
  411. `l18n <https://pypi.org/project/l18n/>`_ package can be used to access
  412. these translations from Python.
  413. License
  414. ~~~~~~~
  415. MIT license.
  416. This code is also available as part of Zope 3 under the Zope Public
  417. License, Version 2.1 (ZPL).
  418. I'm happy to relicense this code if necessary for inclusion in other
  419. open source projects.
  420. Latest Versions
  421. ~~~~~~~~~~~~~~~
  422. This package will be updated after releases of the Olson timezone
  423. database. The latest version can be downloaded from the `Python Package
  424. Index <https://pypi.org/project/pytz/>`_. The code that is used
  425. to generate this distribution is hosted on launchpad.net and available
  426. using git::
  427. git clone https://git.launchpad.net/pytz
  428. A mirror on github is also available at https://github.com/stub42/pytz
  429. Announcements of new releases are made on
  430. `Launchpad <https://launchpad.net/pytz>`_, and the
  431. `Atom feed <http://feeds.launchpad.net/pytz/announcements.atom>`_
  432. hosted there.
  433. Bugs, Feature Requests & Patches
  434. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  435. Bugs can be reported using `Launchpad <https://bugs.launchpad.net/pytz>`__.
  436. Issues & Limitations
  437. ~~~~~~~~~~~~~~~~~~~~
  438. - Offsets from UTC are rounded to the nearest whole minute, so timezones
  439. such as Europe/Amsterdam pre 1937 will be up to 30 seconds out. This
  440. is a limitation of the Python datetime library.
  441. - If you think a timezone definition is incorrect, I probably can't fix
  442. it. pytz is a direct translation of the Olson timezone database, and
  443. changes to the timezone definitions need to be made to this source.
  444. If you find errors they should be reported to the time zone mailing
  445. list, linked from http://www.iana.org/time-zones.
  446. Further Reading
  447. ~~~~~~~~~~~~~~~
  448. More info than you want to know about timezones:
  449. http://www.twinsun.com/tz/tz-link.htm
  450. Contact
  451. ~~~~~~~
  452. Stuart Bishop <stuart@stuartbishop.net>