README.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 savings, 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)
  66. '2002-10-27 12:00:00 AMT+0020'
  67. It is safe for timezones without daylight savings trasitions though, such
  68. as UTC:
  69. >>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=pytz.utc).strftime(fmt)
  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 savings time
  81. and other timezone transitions. In this example, ``loc_dt`` is set
  82. to the instant when daylight savings 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 also needs special attention. We also need
  104. to use the ``normalize()`` method to ensure the conversion is correct.
  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 = au_tz.normalize(utc_dt.astimezone(au_tz))
  110. >>> au_dt.strftime(fmt)
  111. '2006-03-27 08:34:59 EST+1100'
  112. >>> utc_dt2 = utc.normalize(au_dt.astimezone(utc))
  113. >>> utc_dt2.strftime(fmt)
  114. '2006-03-26 21:34:59 UTC+0000'
  115. You can take shortcuts when dealing with the UTC side of timezone
  116. conversions. ``normalize()`` and ``localize()`` are not really
  117. necessary when there are no daylight savings time transitions to
  118. deal with.
  119. >>> utc_dt = datetime.utcfromtimestamp(1143408899).replace(tzinfo=utc)
  120. >>> utc_dt.strftime(fmt)
  121. '2006-03-26 21:34:59 UTC+0000'
  122. >>> au_tz = timezone('Australia/Sydney')
  123. >>> au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
  124. >>> au_dt.strftime(fmt)
  125. '2006-03-27 08:34:59 EST+1100'
  126. >>> utc_dt2 = au_dt.astimezone(utc)
  127. >>> utc_dt2.strftime(fmt)
  128. '2006-03-26 21:34:59 UTC+0000'
  129. ``tzinfo`` API
  130. --------------
  131. The ``tzinfo`` instances returned by the ``timezone()`` function have
  132. been extended to cope with ambiguous times by adding an ``is_dst``
  133. parameter to the ``utcoffset()``, ``dst()`` && ``tzname()`` methods.
  134. >>> tz = timezone('America/St_Johns')
  135. >>> normal = datetime(2009, 9, 1)
  136. >>> ambiguous = datetime(2009, 10, 31, 23, 30)
  137. The ``is_dst`` parameter is ignored for most timestamps. It is only used
  138. during DST transition ambiguous periods to resulve that ambiguity.
  139. >>> tz.utcoffset(normal, is_dst=True)
  140. datetime.timedelta(-1, 77400)
  141. >>> tz.dst(normal, is_dst=True)
  142. datetime.timedelta(0, 3600)
  143. >>> tz.tzname(normal, is_dst=True)
  144. 'NDT'
  145. >>> tz.utcoffset(ambiguous, is_dst=True)
  146. datetime.timedelta(-1, 77400)
  147. >>> tz.dst(ambiguous, is_dst=True)
  148. datetime.timedelta(0, 3600)
  149. >>> tz.tzname(ambiguous, is_dst=True)
  150. 'NDT'
  151. >>> tz.utcoffset(normal, is_dst=False)
  152. datetime.timedelta(-1, 77400)
  153. >>> tz.dst(normal, is_dst=False)
  154. datetime.timedelta(0, 3600)
  155. >>> tz.tzname(normal, is_dst=False)
  156. 'NDT'
  157. >>> tz.utcoffset(ambiguous, is_dst=False)
  158. datetime.timedelta(-1, 73800)
  159. >>> tz.dst(ambiguous, is_dst=False)
  160. datetime.timedelta(0)
  161. >>> tz.tzname(ambiguous, is_dst=False)
  162. 'NST'
  163. If ``is_dst`` is not specified, ambiguous timestamps will raise
  164. an ``pytz.exceptions.AmbiguousTimeError`` exception.
  165. >>> tz.utcoffset(normal)
  166. datetime.timedelta(-1, 77400)
  167. >>> tz.dst(normal)
  168. datetime.timedelta(0, 3600)
  169. >>> tz.tzname(normal)
  170. 'NDT'
  171. >>> import pytz.exceptions
  172. >>> try:
  173. ... tz.utcoffset(ambiguous)
  174. ... except pytz.exceptions.AmbiguousTimeError:
  175. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  176. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  177. >>> try:
  178. ... tz.dst(ambiguous)
  179. ... except pytz.exceptions.AmbiguousTimeError:
  180. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  181. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  182. >>> try:
  183. ... tz.tzname(ambiguous)
  184. ... except pytz.exceptions.AmbiguousTimeError:
  185. ... print('pytz.exceptions.AmbiguousTimeError: %s' % ambiguous)
  186. pytz.exceptions.AmbiguousTimeError: 2009-10-31 23:30:00
  187. Problems with Localtime
  188. ~~~~~~~~~~~~~~~~~~~~~~~
  189. The major problem we have to deal with is that certain datetimes
  190. may occur twice in a year. For example, in the US/Eastern timezone
  191. on the last Sunday morning in October, the following sequence
  192. happens:
  193. - 01:00 EDT occurs
  194. - 1 hour later, instead of 2:00am the clock is turned back 1 hour
  195. and 01:00 happens again (this time 01:00 EST)
  196. In fact, every instant between 01:00 and 02:00 occurs twice. This means
  197. that if you try and create a time in the 'US/Eastern' timezone using
  198. the standard datetime syntax, there is no way to specify if you meant
  199. before of after the end-of-daylight-savings-time transition.
  200. >>> loc_dt = datetime(2002, 10, 27, 1, 30, 00, tzinfo=eastern)
  201. >>> loc_dt.strftime(fmt)
  202. '2002-10-27 01:30:00 EST-0500'
  203. As you can see, the system has chosen one for you and there is a 50%
  204. chance of it being out by one hour. For some applications, this does
  205. not matter. However, if you are trying to schedule meetings with people
  206. in different timezones or analyze log files it is not acceptable.
  207. The best and simplest solution is to stick with using UTC. The pytz
  208. package encourages using UTC for internal timezone representation by
  209. including a special UTC implementation based on the standard Python
  210. reference implementation in the Python documentation.
  211. The UTC timezone unpickles to be the same instance, and pickles to a
  212. smaller size than other pytz tzinfo instances. The UTC implementation
  213. can be obtained as pytz.utc, pytz.UTC, or pytz.timezone('UTC').
  214. >>> import pickle, pytz
  215. >>> dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
  216. >>> naive = dt.replace(tzinfo=None)
  217. >>> p = pickle.dumps(dt, 1)
  218. >>> naive_p = pickle.dumps(naive, 1)
  219. >>> len(p) - len(naive_p)
  220. 17
  221. >>> new = pickle.loads(p)
  222. >>> new == dt
  223. True
  224. >>> new is dt
  225. False
  226. >>> new.tzinfo is dt.tzinfo
  227. True
  228. >>> pytz.utc is pytz.UTC is pytz.timezone('UTC')
  229. True
  230. Note that this instance is not the same instance (or implementation) as
  231. other timezones with the same meaning (GMT, Greenwich, Universal, etc.).
  232. >>> utc is pytz.timezone('GMT')
  233. False
  234. If you insist on working with local times, this library provides a
  235. facility for constructing them unambiguously:
  236. >>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
  237. >>> est_dt = eastern.localize(loc_dt, is_dst=True)
  238. >>> edt_dt = eastern.localize(loc_dt, is_dst=False)
  239. >>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))
  240. 2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500
  241. If you pass None as the is_dst flag to localize(), pytz will refuse to
  242. guess and raise exceptions if you try to build ambiguous or non-existent
  243. times.
  244. For example, 1:30am on 27th Oct 2002 happened twice in the US/Eastern
  245. timezone when the clocks where put back at the end of Daylight Savings
  246. Time:
  247. >>> dt = datetime(2002, 10, 27, 1, 30, 00)
  248. >>> try:
  249. ... eastern.localize(dt, is_dst=None)
  250. ... except pytz.exceptions.AmbiguousTimeError:
  251. ... print('pytz.exceptions.AmbiguousTimeError: %s' % dt)
  252. pytz.exceptions.AmbiguousTimeError: 2002-10-27 01:30:00
  253. Similarly, 2:30am on 7th April 2002 never happened at all in the
  254. US/Eastern timezone, as the clocks where put forward at 2:00am skipping
  255. the entire hour:
  256. >>> dt = datetime(2002, 4, 7, 2, 30, 00)
  257. >>> try:
  258. ... eastern.localize(dt, is_dst=None)
  259. ... except pytz.exceptions.NonExistentTimeError:
  260. ... print('pytz.exceptions.NonExistentTimeError: %s' % dt)
  261. pytz.exceptions.NonExistentTimeError: 2002-04-07 02:30:00
  262. Both of these exceptions share a common base class to make error handling
  263. easier:
  264. >>> isinstance(pytz.AmbiguousTimeError(), pytz.InvalidTimeError)
  265. True
  266. >>> isinstance(pytz.NonExistentTimeError(), pytz.InvalidTimeError)
  267. True
  268. Although ``localize()`` handles many cases, it is still not possible
  269. to handle all. In cases where countries change their timezone definitions,
  270. cases like the end-of-daylight-savings-time occur with no way of resolving
  271. the ambiguity. For example, in 1915 Warsaw switched from Warsaw time to
  272. Central European time. So at the stroke of midnight on August 5th 1915
  273. the clocks were wound back 24 minutes creating an ambiguous time period
  274. that cannot be specified without referring to the timezone abbreviation
  275. or the actual UTC offset. In this case midnight happened twice, neither
  276. time during a daylight savings time period:
  277. >>> warsaw = pytz.timezone('Europe/Warsaw')
  278. >>> loc_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)
  279. >>> loc_dt1.strftime(fmt)
  280. '1915-08-04 23:59:59 WMT+0124'
  281. >>> loc_dt2 = warsaw.localize(datetime(1915, 8, 5, 00, 00, 00), is_dst=False)
  282. >>> loc_dt2.strftime(fmt)
  283. '1915-08-05 00:00:00 CET+0100'
  284. >>> str(loc_dt2 - loc_dt1)
  285. '0:24:01'
  286. The only way of creating a time during the missing 24 minutes is
  287. converting from another timezone - because neither of the timezones
  288. involved where in daylight savings mode the API simply provides no way
  289. to express it:
  290. >>> utc_dt = datetime(1915, 8, 4, 22, 36, tzinfo=pytz.utc)
  291. >>> utc_dt.astimezone(warsaw).strftime(fmt)
  292. '1915-08-04 23:36:00 CET+0100'
  293. The standard Python way of handling all these ambiguities is not to
  294. handle them, such as demonstrated in this example using the US/Eastern
  295. timezone definition from the Python documentation (Note that this
  296. implementation only works for dates between 1987 and 2006 - it is
  297. included for tests only!):
  298. >>> from pytz.reference import Eastern # pytz.reference only for tests
  299. >>> dt = datetime(2002, 10, 27, 0, 30, tzinfo=Eastern)
  300. >>> str(dt)
  301. '2002-10-27 00:30:00-04:00'
  302. >>> str(dt + timedelta(hours=1))
  303. '2002-10-27 01:30:00-05:00'
  304. >>> str(dt + timedelta(hours=2))
  305. '2002-10-27 02:30:00-05:00'
  306. >>> str(dt + timedelta(hours=3))
  307. '2002-10-27 03:30:00-05:00'
  308. Notice the first two results? At first glance you might think they are
  309. correct, but taking the UTC offset into account you find that they are
  310. actually two hours appart instead of the 1 hour we asked for.
  311. >>> from pytz.reference import UTC # pytz.reference only for tests
  312. >>> str(dt.astimezone(UTC))
  313. '2002-10-27 04:30:00+00:00'
  314. >>> str((dt + timedelta(hours=1)).astimezone(UTC))
  315. '2002-10-27 06:30:00+00:00'
  316. Country Information
  317. ~~~~~~~~~~~~~~~~~~~
  318. A mechanism is provided to access the timezones commonly in use
  319. for a particular country, looked up using the ISO 3166 country code.
  320. It returns a list of strings that can be used to retrieve the relevant
  321. tzinfo instance using ``pytz.timezone()``:
  322. >>> print(' '.join(pytz.country_timezones['nz']))
  323. Pacific/Auckland Pacific/Chatham
  324. The Olson database comes with a ISO 3166 country code to English country
  325. name mapping that pytz exposes as a dictionary:
  326. >>> print(pytz.country_names['nz'])
  327. New Zealand
  328. What is UTC
  329. ~~~~~~~~~~~
  330. 'UTC' is Universal Time, also known as Greenwich Mean Time or GMT
  331. in the United Kingdom. All other timezones are given as offsets from
  332. UTC. No daylight savings time occurs in UTC, making it a useful timezone
  333. to perform date arithmetic without worrying about the confusion and
  334. ambiguities caused by daylight savings time transitions, your country
  335. changing its timezone, or mobile computers that move roam through
  336. multiple timezones.
  337. Helpers
  338. ~~~~~~~
  339. There are two lists of timezones provided.
  340. ``all_timezones`` is the exhaustive list of the timezone names that can
  341. be used.
  342. >>> from pytz import all_timezones
  343. >>> len(all_timezones) >= 500
  344. True
  345. >>> 'Etc/Greenwich' in all_timezones
  346. True
  347. ``common_timezones`` is a list of useful, current timezones. It doesn't
  348. contain deprecated zones or historical zones, except for a few I've
  349. deemed in common usage, such as US/Eastern (open a bug report if you
  350. think other timezones are deserving of being included here). It is also
  351. a sequence of strings.
  352. >>> from pytz import common_timezones
  353. >>> len(common_timezones) < len(all_timezones)
  354. True
  355. >>> 'Etc/Greenwich' in common_timezones
  356. False
  357. >>> 'Australia/Melbourne' in common_timezones
  358. True
  359. >>> 'US/Eastern' in common_timezones
  360. True
  361. >>> 'Canada/Eastern' in common_timezones
  362. True
  363. >>> 'US/Pacific-New' in all_timezones
  364. True
  365. >>> 'US/Pacific-New' in common_timezones
  366. False
  367. Both ``common_timezones`` and ``all_timezones`` are alphabetically
  368. sorted:
  369. >>> common_timezones_dupe = common_timezones[:]
  370. >>> common_timezones_dupe.sort()
  371. >>> common_timezones == common_timezones_dupe
  372. True
  373. >>> all_timezones_dupe = all_timezones[:]
  374. >>> all_timezones_dupe.sort()
  375. >>> all_timezones == all_timezones_dupe
  376. True
  377. ``all_timezones`` and ``common_timezones`` are also available as sets.
  378. >>> from pytz import all_timezones_set, common_timezones_set
  379. >>> 'US/Eastern' in all_timezones_set
  380. True
  381. >>> 'US/Eastern' in common_timezones_set
  382. True
  383. >>> 'Australia/Victoria' in common_timezones_set
  384. False
  385. You can also retrieve lists of timezones used by particular countries
  386. using the ``country_timezones()`` function. It requires an ISO-3166
  387. two letter country code.
  388. >>> from pytz import country_timezones
  389. >>> print(' '.join(country_timezones('ch')))
  390. Europe/Zurich
  391. >>> print(' '.join(country_timezones('CH')))
  392. Europe/Zurich
  393. License
  394. ~~~~~~~
  395. MIT license.
  396. This code is also available as part of Zope 3 under the Zope Public
  397. License, Version 2.1 (ZPL).
  398. I'm happy to relicense this code if necessary for inclusion in other
  399. open source projects.
  400. Latest Versions
  401. ~~~~~~~~~~~~~~~
  402. This package will be updated after releases of the Olson timezone
  403. database. The latest version can be downloaded from the `Python Package
  404. Index <http://pypi.python.org/pypi/pytz/>`_. The code that is used
  405. to generate this distribution is hosted on launchpad.net and available
  406. using the `Bazaar version control system <http://bazaar-vcs.org>`_
  407. using::
  408. bzr branch lp:pytz
  409. Announcements of new releases are made on
  410. `Launchpad <https://launchpad.net/pytz>`_, and the
  411. `Atom feed <http://feeds.launchpad.net/pytz/announcements.atom>`_
  412. hosted there.
  413. Bugs, Feature Requests & Patches
  414. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  415. Bugs can be reported using `Launchpad <https://bugs.launchpad.net/pytz>`_.
  416. Issues & Limitations
  417. ~~~~~~~~~~~~~~~~~~~~
  418. - Offsets from UTC are rounded to the nearest whole minute, so timezones
  419. such as Europe/Amsterdam pre 1937 will be up to 30 seconds out. This
  420. is a limitation of the Python datetime library.
  421. - If you think a timezone definition is incorrect, I probably can't fix
  422. it. pytz is a direct translation of the Olson timezone database, and
  423. changes to the timezone definitions need to be made to this source.
  424. If you find errors they should be reported to the time zone mailing
  425. list, linked from http://www.iana.org/time-zones.
  426. Further Reading
  427. ~~~~~~~~~~~~~~~
  428. More info than you want to know about timezones:
  429. http://www.twinsun.com/tz/tz-link.htm
  430. Contact
  431. ~~~~~~~
  432. Stuart Bishop <stuart@stuartbishop.net>