timezones.txt 25 KB

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