timezones.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. ==========
  2. Time zones
  3. ==========
  4. .. _time-zones-overview:
  5. Overview
  6. ========
  7. When support for time zones is enabled, Django stores datetime information in
  8. UTC in the database, uses time-zone-aware datetime objects internally, and
  9. translates them to the end user's time zone in templates and forms.
  10. This is handy if your users live in more than one time zone and you want to
  11. display datetime information according to each user's wall clock.
  12. Even if your website is available in only one time zone, it's still good
  13. practice to store data in UTC in your database. The main reason is Daylight
  14. Saving Time (DST). Many countries have a system of DST, where clocks are moved
  15. forward in spring and backward in autumn. If you're working in local time,
  16. you're likely to encounter errors twice a year, when the transitions happen.
  17. (The pytz_ documentation discusses `these issues`_ in greater detail.) This
  18. probably doesn't matter for your blog, but it's a problem if you over-bill or
  19. under-bill your customers by one hour, twice a year, every year. The solution
  20. to this problem is to use UTC in the code and use local time only when
  21. interacting with end users.
  22. Time zone support is disabled by default. To enable it, set :setting:`USE_TZ =
  23. True <USE_TZ>` in your settings file. Time zone support uses pytz_, which is
  24. installed when you install Django.
  25. .. versionchanged:: 1.11
  26. Older versions don't require ``pytz`` or install it automatically.
  27. .. note::
  28. The default :file:`settings.py` file created by :djadmin:`django-admin
  29. startproject <startproject>` includes :setting:`USE_TZ = True <USE_TZ>`
  30. for convenience.
  31. .. note::
  32. There is also an independent but related :setting:`USE_L10N` setting that
  33. controls whether Django should activate format localization. See
  34. :doc:`/topics/i18n/formatting` for more details.
  35. If you're wrestling with a particular problem, start with the :ref:`time zone
  36. FAQ <time-zones-faq>`.
  37. Concepts
  38. ========
  39. .. _naive_vs_aware_datetimes:
  40. Naive and aware datetime objects
  41. --------------------------------
  42. Python's :class:`datetime.datetime` objects have a ``tzinfo`` attribute that
  43. can be used to store time zone information, represented as an instance of a
  44. subclass of :class:`datetime.tzinfo`. When this attribute is set and describes
  45. an offset, a datetime object is **aware**. Otherwise, it's **naive**.
  46. You can use :func:`~django.utils.timezone.is_aware` and
  47. :func:`~django.utils.timezone.is_naive` to determine whether datetimes are
  48. aware or naive.
  49. When time zone support is disabled, Django uses naive datetime objects in local
  50. time. This is simple and sufficient for many use cases. In this mode, to obtain
  51. the current time, you would write::
  52. import datetime
  53. now = datetime.datetime.now()
  54. When time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses
  55. time-zone-aware datetime objects. If your code creates datetime objects, they
  56. should be aware too. In this mode, the example above becomes::
  57. from django.utils import timezone
  58. now = timezone.now()
  59. .. warning::
  60. Dealing with aware datetime objects isn't always intuitive. For instance,
  61. the ``tzinfo`` argument of the standard datetime constructor doesn't work
  62. reliably for time zones with DST. Using UTC is generally safe; if you're
  63. using other time zones, you should review the `pytz`_ documentation
  64. carefully.
  65. .. note::
  66. Python's :class:`datetime.time` objects also feature a ``tzinfo``
  67. attribute, and PostgreSQL has a matching ``time with time zone`` type.
  68. However, as PostgreSQL's docs put it, this type "exhibits properties which
  69. lead to questionable usefulness".
  70. Django only supports naive time objects and will raise an exception if you
  71. attempt to save an aware time object, as a timezone for a time with no
  72. associated date does not make sense.
  73. .. _naive-datetime-objects:
  74. Interpretation of naive datetime objects
  75. ----------------------------------------
  76. When :setting:`USE_TZ` is ``True``, Django still accepts naive datetime
  77. objects, in order to preserve backwards-compatibility. When the database layer
  78. receives one, it attempts to make it aware by interpreting it in the
  79. :ref:`default time zone <default-current-time-zone>` and raises a warning.
  80. Unfortunately, during DST transitions, some datetimes don't exist or are
  81. ambiguous. In such situations, pytz_ raises an exception. That's why you should
  82. always create aware datetime objects when time zone support is enabled.
  83. In practice, this is rarely an issue. Django gives you aware datetime objects
  84. in the models and forms, and most often, new datetime objects are created from
  85. existing ones through :class:`~datetime.timedelta` arithmetic. The only
  86. datetime that's often created in application code is the current time, and
  87. :func:`timezone.now() <django.utils.timezone.now>` automatically does the
  88. right thing.
  89. .. _default-current-time-zone:
  90. Default time zone and current time zone
  91. ---------------------------------------
  92. The **default time zone** is the time zone defined by the :setting:`TIME_ZONE`
  93. setting.
  94. The **current time zone** is the time zone that's used for rendering.
  95. You should set the current time zone to the end user's actual time zone with
  96. :func:`~django.utils.timezone.activate`. Otherwise, the default time zone is
  97. used.
  98. .. note::
  99. As explained in the documentation of :setting:`TIME_ZONE`, Django sets
  100. environment variables so that its process runs in the default time zone.
  101. This happens regardless of the value of :setting:`USE_TZ` and of the
  102. current time zone.
  103. When :setting:`USE_TZ` is ``True``, this is useful to preserve
  104. backwards-compatibility with applications that still rely on local time.
  105. However, :ref:`as explained above <naive-datetime-objects>`, this isn't
  106. entirely reliable, and you should always work with aware datetimes in UTC
  107. in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp`
  108. and set the ``tz`` parameter to :data:`~django.utils.timezone.utc`.
  109. Selecting the current time zone
  110. -------------------------------
  111. The current time zone is the equivalent of the current :term:`locale <locale
  112. name>` for translations. However, there's no equivalent of the
  113. ``Accept-Language`` HTTP header that Django could use to determine the user's
  114. time zone automatically. Instead, Django provides :ref:`time zone selection
  115. functions <time-zone-selection-functions>`. Use them to build the time zone
  116. selection logic that makes sense for you.
  117. Most websites that care about time zones just ask users in which time zone they
  118. live and store this information in the user's profile. For anonymous users,
  119. they use the time zone of their primary audience or UTC. pytz_ provides
  120. helpers_, like a list of time zones per country, that you can use to pre-select
  121. the most likely choices.
  122. Here's an example that stores the current timezone in the session. (It skips
  123. error handling entirely for the sake of simplicity.)
  124. Add the following middleware to :setting:`MIDDLEWARE`::
  125. import pytz
  126. from django.utils import timezone
  127. from django.utils.deprecation import MiddlewareMixin
  128. class TimezoneMiddleware(MiddlewareMixin):
  129. def process_request(self, request):
  130. tzname = request.session.get('django_timezone')
  131. if tzname:
  132. timezone.activate(pytz.timezone(tzname))
  133. else:
  134. timezone.deactivate()
  135. Create a view that can set the current timezone::
  136. from django.shortcuts import redirect, render
  137. def set_timezone(request):
  138. if request.method == 'POST':
  139. request.session['django_timezone'] = request.POST['timezone']
  140. return redirect('/')
  141. else:
  142. return render(request, 'template.html', {'timezones': pytz.common_timezones})
  143. Include a form in ``template.html`` that will ``POST`` to this view:
  144. .. code-block:: html+django
  145. {% load tz %}
  146. {% get_current_timezone as TIME_ZONE %}
  147. <form action="{% url 'set_timezone' %}" method="POST">
  148. {% csrf_token %}
  149. <label for="timezone">Time zone:</label>
  150. <select name="timezone">
  151. {% for tz in timezones %}
  152. <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option>
  153. {% endfor %}
  154. </select>
  155. <input type="submit" value="Set" />
  156. </form>
  157. .. _time-zones-in-forms:
  158. Time zone aware input in forms
  159. ==============================
  160. When you enable time zone support, Django interprets datetimes entered in
  161. forms in the :ref:`current time zone <default-current-time-zone>` and returns
  162. aware datetime objects in ``cleaned_data``.
  163. If the current time zone raises an exception for datetimes that don't exist or
  164. are ambiguous because they fall in a DST transition (the timezones provided by
  165. pytz_ do this), such datetimes will be reported as invalid values.
  166. .. _time-zones-in-templates:
  167. Time zone aware output in templates
  168. ===================================
  169. When you enable time zone support, Django converts aware datetime objects to
  170. the :ref:`current time zone <default-current-time-zone>` when they're rendered
  171. in templates. This behaves very much like :doc:`format localization
  172. </topics/i18n/formatting>`.
  173. .. warning::
  174. Django doesn't convert naive datetime objects, because they could be
  175. ambiguous, and because your code should never produce naive datetimes when
  176. time zone support is enabled. However, you can force conversion with the
  177. template filters described below.
  178. Conversion to local time isn't always appropriate -- you may be generating
  179. output for computers rather than for humans. The following filters and tags,
  180. provided by the ``tz`` template tag library, allow you to control the time zone
  181. conversions.
  182. .. highlight:: html+django
  183. Template tags
  184. -------------
  185. .. templatetag:: localtime
  186. ``localtime``
  187. ~~~~~~~~~~~~~
  188. Enables or disables conversion of aware datetime objects to the current time
  189. zone in the contained block.
  190. This tag has exactly the same effects as the :setting:`USE_TZ` setting as far
  191. as the template engine is concerned. It allows a more fine grained control of
  192. conversion.
  193. To activate or deactivate conversion for a template block, use::
  194. {% load tz %}
  195. {% localtime on %}
  196. {{ value }}
  197. {% endlocaltime %}
  198. {% localtime off %}
  199. {{ value }}
  200. {% endlocaltime %}
  201. .. note::
  202. The value of :setting:`USE_TZ` isn't respected inside of a
  203. ``{% localtime %}`` block.
  204. .. templatetag:: timezone
  205. ``timezone``
  206. ~~~~~~~~~~~~
  207. Sets or unsets the current time zone in the contained block. When the current
  208. time zone is unset, the default time zone applies.
  209. ::
  210. {% load tz %}
  211. {% timezone "Europe/Paris" %}
  212. Paris time: {{ value }}
  213. {% endtimezone %}
  214. {% timezone None %}
  215. Server time: {{ value }}
  216. {% endtimezone %}
  217. .. templatetag:: get_current_timezone
  218. ``get_current_timezone``
  219. ~~~~~~~~~~~~~~~~~~~~~~~~
  220. You can get the name of the current time zone using the
  221. ``get_current_timezone`` tag::
  222. {% get_current_timezone as TIME_ZONE %}
  223. Alternatively, you can activate the
  224. :func:`~django.template.context_processors.tz` context processor and
  225. use the ``TIME_ZONE`` context variable.
  226. Template filters
  227. ----------------
  228. These filters accept both aware and naive datetimes. For conversion purposes,
  229. they assume that naive datetimes are in the default time zone. They always
  230. return aware datetimes.
  231. .. templatefilter:: localtime
  232. ``localtime``
  233. ~~~~~~~~~~~~~
  234. Forces conversion of a single value to the current time zone.
  235. For example::
  236. {% load tz %}
  237. {{ value|localtime }}
  238. .. templatefilter:: utc
  239. ``utc``
  240. ~~~~~~~
  241. Forces conversion of a single value to UTC.
  242. For example::
  243. {% load tz %}
  244. {{ value|utc }}
  245. .. templatefilter:: timezone
  246. ``timezone``
  247. ~~~~~~~~~~~~
  248. Forces conversion of a single value to an arbitrary timezone.
  249. The argument must be an instance of a :class:`~datetime.tzinfo` subclass or a
  250. time zone name.
  251. For example::
  252. {% load tz %}
  253. {{ value|timezone:"Europe/Paris" }}
  254. .. highlight:: python
  255. .. _time-zones-migration-guide:
  256. Migration guide
  257. ===============
  258. Here's how to migrate a project that was started before Django supported time
  259. zones.
  260. Database
  261. --------
  262. PostgreSQL
  263. ~~~~~~~~~~
  264. The PostgreSQL backend stores datetimes as ``timestamp with time zone``. In
  265. practice, this means it converts datetimes from the connection's time zone to
  266. UTC on storage, and from UTC to the connection's time zone on retrieval.
  267. As a consequence, if you're using PostgreSQL, you can switch between ``USE_TZ
  268. = False`` and ``USE_TZ = True`` freely. The database connection's time zone
  269. will be set to :setting:`TIME_ZONE` or ``UTC`` respectively, so that Django
  270. obtains correct datetimes in all cases. You don't need to perform any data
  271. conversions.
  272. Other databases
  273. ~~~~~~~~~~~~~~~
  274. Other backends store datetimes without time zone information. If you switch
  275. from ``USE_TZ = False`` to ``USE_TZ = True``, you must convert your data from
  276. local time to UTC -- which isn't deterministic if your local time has DST.
  277. Code
  278. ----
  279. The first step is to add :setting:`USE_TZ = True <USE_TZ>` to your settings
  280. file. At this point, things should mostly work. If you create naive datetime
  281. objects in your code, Django makes them aware when necessary.
  282. However, these conversions may fail around DST transitions, which means you
  283. aren't getting the full benefits of time zone support yet. Also, you're likely
  284. to run into a few problems because it's impossible to compare a naive datetime
  285. with an aware datetime. Since Django now gives you aware datetimes, you'll get
  286. exceptions wherever you compare a datetime that comes from a model or a form
  287. with a naive datetime that you've created in your code.
  288. So the second step is to refactor your code wherever you instantiate datetime
  289. objects to make them aware. This can be done incrementally.
  290. :mod:`django.utils.timezone` defines some handy helpers for compatibility
  291. code: :func:`~django.utils.timezone.now`,
  292. :func:`~django.utils.timezone.is_aware`,
  293. :func:`~django.utils.timezone.is_naive`,
  294. :func:`~django.utils.timezone.make_aware`, and
  295. :func:`~django.utils.timezone.make_naive`.
  296. Finally, in order to help you locate code that needs upgrading, Django raises
  297. a warning when you attempt to save a naive datetime to the database::
  298. RuntimeWarning: DateTimeField ModelName.field_name received a naive
  299. datetime (2012-01-01 00:00:00) while time zone support is active.
  300. During development, you can turn such warnings into exceptions and get a
  301. traceback by adding the following to your settings file::
  302. import warnings
  303. warnings.filterwarnings(
  304. 'error', r"DateTimeField .* received a naive datetime",
  305. RuntimeWarning, r'django\.db\.models\.fields',
  306. )
  307. Fixtures
  308. --------
  309. When serializing an aware datetime, the UTC offset is included, like this::
  310. "2011-09-01T13:20:30+03:00"
  311. For a naive datetime, it obviously isn't::
  312. "2011-09-01T13:20:30"
  313. For models with :class:`~django.db.models.DateTimeField`\ s, this difference
  314. makes it impossible to write a fixture that works both with and without time
  315. zone support.
  316. Fixtures generated with ``USE_TZ = False``, or before Django 1.4, use the
  317. "naive" format. If your project contains such fixtures, after you enable time
  318. zone support, you'll see :exc:`RuntimeWarning`\ s when you load them. To get
  319. rid of the warnings, you must convert your fixtures to the "aware" format.
  320. You can regenerate fixtures with :djadmin:`loaddata` then :djadmin:`dumpdata`.
  321. Or, if they're small enough, you can simply edit them to add the UTC offset
  322. that matches your :setting:`TIME_ZONE` to each serialized datetime.
  323. .. _time-zones-faq:
  324. FAQ
  325. ===
  326. Setup
  327. -----
  328. 1. **I don't need multiple time zones. Should I enable time zone support?**
  329. Yes. When time zone support is enabled, Django uses a more accurate model
  330. of local time. This shields you from subtle and unreproducible bugs around
  331. Daylight Saving Time (DST) transitions.
  332. When you enable time zone support, you'll encounter some errors because
  333. you're using naive datetimes where Django expects aware datetimes. Such
  334. errors show up when running tests and they're easy to fix. You'll quickly
  335. learn how to avoid invalid operations.
  336. On the other hand, bugs caused by the lack of time zone support are much
  337. harder to prevent, diagnose and fix. Anything that involves scheduled tasks
  338. or datetime arithmetic is a candidate for subtle bugs that will bite you
  339. only once or twice a year.
  340. For these reasons, time zone support is enabled by default in new projects,
  341. and you should keep it unless you have a very good reason not to.
  342. 2. **I've enabled time zone support. Am I safe?**
  343. Maybe. You're better protected from DST-related bugs, but you can still
  344. shoot yourself in the foot by carelessly turning naive datetimes into aware
  345. datetimes, and vice-versa.
  346. If your application connects to other systems -- for instance, if it queries
  347. a Web service -- make sure datetimes are properly specified. To transmit
  348. datetimes safely, their representation should include the UTC offset, or
  349. their values should be in UTC (or both!).
  350. Finally, our calendar system contains interesting traps for computers::
  351. >>> import datetime
  352. >>> def one_year_before(value): # DON'T DO THAT!
  353. ... return value.replace(year=value.year - 1)
  354. >>> one_year_before(datetime.datetime(2012, 3, 1, 10, 0))
  355. datetime.datetime(2011, 3, 1, 10, 0)
  356. >>> one_year_before(datetime.datetime(2012, 2, 29, 10, 0))
  357. Traceback (most recent call last):
  358. ...
  359. ValueError: day is out of range for month
  360. (To implement this function, you must decide whether 2012-02-29 minus
  361. one year is 2011-02-28 or 2011-03-01, which depends on your business
  362. requirements.)
  363. 3. **How do I interact with a database that stores datetimes in local time?**
  364. Set the :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` option to the appropriate
  365. time zone for this database in the :setting:`DATABASES` setting.
  366. This is useful for connecting to a database that doesn't support time zones
  367. and that isn't managed by Django when :setting:`USE_TZ` is ``True``.
  368. Troubleshooting
  369. ---------------
  370. 1. **My application crashes with** ``TypeError: can't compare offset-naive``
  371. ``and offset-aware datetimes`` **-- what's wrong?**
  372. Let's reproduce this error by comparing a naive and an aware datetime::
  373. >>> import datetime
  374. >>> from django.utils import timezone
  375. >>> naive = datetime.datetime.utcnow()
  376. >>> aware = timezone.now()
  377. >>> naive == aware
  378. Traceback (most recent call last):
  379. ...
  380. TypeError: can't compare offset-naive and offset-aware datetimes
  381. If you encounter this error, most likely your code is comparing these two
  382. things:
  383. - a datetime provided by Django -- for instance, a value read from a form or
  384. a model field. Since you enabled time zone support, it's aware.
  385. - a datetime generated by your code, which is naive (or you wouldn't be
  386. reading this).
  387. Generally, the correct solution is to change your code to use an aware
  388. datetime instead.
  389. If you're writing a pluggable application that's expected to work
  390. independently of the value of :setting:`USE_TZ`, you may find
  391. :func:`django.utils.timezone.now` useful. This function returns the current
  392. date and time as a naive datetime when ``USE_TZ = False`` and as an aware
  393. datetime when ``USE_TZ = True``. You can add or subtract
  394. :class:`datetime.timedelta` as needed.
  395. 2. **I see lots of** ``RuntimeWarning: DateTimeField received a naive
  396. datetime`` ``(YYYY-MM-DD HH:MM:SS)`` ``while time zone support is active``
  397. **-- is that bad?**
  398. When time zone support is enabled, the database layer expects to receive
  399. only aware datetimes from your code. This warning occurs when it receives a
  400. naive datetime. This indicates that you haven't finished porting your code
  401. for time zone support. Please refer to the :ref:`migration guide
  402. <time-zones-migration-guide>` for tips on this process.
  403. In the meantime, for backwards compatibility, the datetime is considered to
  404. be in the default time zone, which is generally what you expect.
  405. 3. ``now.date()`` **is yesterday! (or tomorrow)**
  406. If you've always used naive datetimes, you probably believe that you can
  407. convert a datetime to a date by calling its :meth:`~datetime.datetime.date`
  408. method. You also consider that a :class:`~datetime.date` is a lot like a
  409. :class:`~datetime.datetime`, except that it's less accurate.
  410. None of this is true in a time zone aware environment::
  411. >>> import datetime
  412. >>> import pytz
  413. >>> paris_tz = pytz.timezone("Europe/Paris")
  414. >>> new_york_tz = pytz.timezone("America/New_York")
  415. >>> paris = paris_tz.localize(datetime.datetime(2012, 3, 3, 1, 30))
  416. # This is the correct way to convert between time zones with pytz.
  417. >>> new_york = new_york_tz.normalize(paris.astimezone(new_york_tz))
  418. >>> paris == new_york, paris.date() == new_york.date()
  419. (True, False)
  420. >>> paris - new_york, paris.date() - new_york.date()
  421. (datetime.timedelta(0), datetime.timedelta(1))
  422. >>> paris
  423. datetime.datetime(2012, 3, 3, 1, 30, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
  424. >>> new_york
  425. datetime.datetime(2012, 3, 2, 19, 30, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
  426. As this example shows, the same datetime has a different date, depending on
  427. the time zone in which it is represented. But the real problem is more
  428. fundamental.
  429. A datetime represents a **point in time**. It's absolute: it doesn't depend
  430. on anything. On the contrary, a date is a **calendaring concept**. It's a
  431. period of time whose bounds depend on the time zone in which the date is
  432. considered. As you can see, these two concepts are fundamentally different,
  433. and converting a datetime to a date isn't a deterministic operation.
  434. What does this mean in practice?
  435. Generally, you should avoid converting a :class:`~datetime.datetime` to
  436. :class:`~datetime.date`. For instance, you can use the :tfilter:`date`
  437. template filter to only show the date part of a datetime. This filter will
  438. convert the datetime into the current time zone before formatting it,
  439. ensuring the results appear correctly.
  440. If you really need to do the conversion yourself, you must ensure the
  441. datetime is converted to the appropriate time zone first. Usually, this
  442. will be the current timezone::
  443. >>> from django.utils import timezone
  444. >>> timezone.activate(pytz.timezone("Asia/Singapore"))
  445. # For this example, we just set the time zone to Singapore, but here's how
  446. # you would obtain the current time zone in the general case.
  447. >>> current_tz = timezone.get_current_timezone()
  448. # Again, this is the correct way to convert between time zones with pytz.
  449. >>> local = current_tz.normalize(paris.astimezone(current_tz))
  450. >>> local
  451. datetime.datetime(2012, 3, 3, 8, 30, tzinfo=<DstTzInfo 'Asia/Singapore' SGT+8:00:00 STD>)
  452. >>> local.date()
  453. datetime.date(2012, 3, 3)
  454. 4. **I get an error** "``Are time zone definitions for your database
  455. installed?``"
  456. If you are using MySQL, see the :ref:`mysql-time-zone-definitions` section
  457. of the MySQL notes for instructions on loading time zone definitions.
  458. Usage
  459. -----
  460. 1. **I have a string** ``"2012-02-21 10:28:45"`` **and I know it's in the**
  461. ``"Europe/Helsinki"`` **time zone. How do I turn that into an aware
  462. datetime?**
  463. This is exactly what pytz_ is for.
  464. >>> from django.utils.dateparse import parse_datetime
  465. >>> naive = parse_datetime("2012-02-21 10:28:45")
  466. >>> import pytz
  467. >>> pytz.timezone("Europe/Helsinki").localize(naive, is_dst=None)
  468. datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)
  469. Note that ``localize`` is a pytz extension to the :class:`~datetime.tzinfo`
  470. API. Also, you may want to catch ``pytz.InvalidTimeError``. The
  471. documentation of pytz contains `more examples`_. You should review it
  472. before attempting to manipulate aware datetimes.
  473. 2. **How can I obtain the local time in the current time zone?**
  474. Well, the first question is, do you really need to?
  475. You should only use local time when you're interacting with humans, and the
  476. template layer provides :ref:`filters and tags <time-zones-in-templates>`
  477. to convert datetimes to the time zone of your choice.
  478. Furthermore, Python knows how to compare aware datetimes, taking into
  479. account UTC offsets when necessary. It's much easier (and possibly faster)
  480. to write all your model and view code in UTC. So, in most circumstances,
  481. the datetime in UTC returned by :func:`django.utils.timezone.now` will be
  482. sufficient.
  483. For the sake of completeness, though, if you really want the local time
  484. in the current time zone, here's how you can obtain it::
  485. >>> from django.utils import timezone
  486. >>> timezone.localtime(timezone.now())
  487. datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
  488. In this example, the current time zone is ``"Europe/Paris"``.
  489. 3. **How can I see all available time zones?**
  490. pytz_ provides helpers_, including a list of current time zones and a list
  491. of all available time zones -- some of which are only of historical
  492. interest.
  493. .. _pytz: http://pytz.sourceforge.net/
  494. .. _more examples: http://pytz.sourceforge.net/#example-usage
  495. .. _these issues: http://pytz.sourceforge.net/#problems-with-localtime
  496. .. _helpers: http://pytz.sourceforge.net/#helpers
  497. .. _tz database: https://en.wikipedia.org/wiki/Tz_database