127

Right now I use

import datetime
print(datetime.datetime.now().strftime("%X"))

to display the current time as a string.
Problem is, my computer is running in Europe/Berlin time zone, and the offset of +2 to UTC is not accounted here. Instead of 19:22:26 it should display 21:22:26 Also different to the other answers I found here, I do not store it by calling

datetime.datetime(2014, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)

but

datetime.datetime.now()

so I tried (and failed) the following:

>>> from pytz import timezone
>>> datetime.datetime.now().astimezone(timezone('Europe/Berlin'))
 ValueError: astimezone() cannot be applied to a naive datetime


Edit:

Answer

Can't post as answer, as this question is marked closed

The server I had this issue with doesn't exists any longer. Anyway, here are some other things worth checking:

  • Is the timezone of your server/system set up correctly?
    • VMs or docker containers might be out of sync with the host, that's worth checking.
  • Is the time on that computer correct? You don't ended up with +2 hours after changing the timezone?
luckydonald
  • 5,976
  • 4
  • 38
  • 58
  • what output are you getting? – Padraic Cunningham Sep 14 '14 at 20:13
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/61221/discussion-between-luckydonald-and-padraic-cunningham). – luckydonald Sep 14 '14 at 20:14
  • related: [How to get current time in Python](http://stackoverflow.com/q/415511/4279) – jfs Sep 17 '14 at 10:11
  • We can directly use `pytz` MODULE – champion-runner Oct 18 '19 at 13:11
  • 1
    @champion-runner The one I already imported above? – luckydonald Oct 18 '19 at 13:13
  • Ok that I just saw **Example**- `tz_London = pytz.timezone('Europe/London') datetime_London = datetime.now(tz_London) print("London time:", datetime_London.strftime("%H:%M:%S"))` – champion-runner Oct 18 '19 at 13:17
  • I wonder if people are actually upvoting my "Answer" above, as being useful. – luckydonald Nov 19 '19 at 15:09
  • Or just the question, saying "me too got this problem" – luckydonald Nov 19 '19 at 15:09
  • Just ran into this issue due to a bug in Python 3.6+. https://bugs.python.org/issue30062. I'm now using: datetime.datetime.now(ZoneInfo("Europe/Amsterdam")). It's a bit of a hack but alas the TZ variable as I have it set can't be used directly by ZoneInfo(...). – Alexander Kellett Jul 23 '21 at 07:43
  • 1
    This was made a duplicate of the other question although only here, I found the plain pytz solution. The other answer only convinced me of not using any local time with pytz at all because of the seasonal time shifts. But for someone who really just wants to show the current time of the place, why not using this pytz way here? Reopen? – questionto42 Sep 13 '21 at 13:38
  • @questionto42: I'd love to have this reopened and allow others than @[jfs](https://stackoverflow.com/users/4279/jfs) to send in answers (jfs then voted to close this for others to answers, thus remaining the only answer to get upvoted on ) – luckydonald Sep 15 '21 at 14:01
  • I cannot find a button to vote Reopen. Cannot you just vote for Reopen? You would get my vote, then we had already two. I do not think that the user jfs did that only to make this a unique answer, though, but I would vote for Reopen for another reason, anyway. – questionto42 Sep 16 '21 at 09:23

1 Answers1

246

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 3
    @AlexanderKellett: I don't see `pytz` being deprecated ([the latest release is Feb 1, 2021](https://pypi.org/project/pytz/#history)) `pytz` is a battle tested library with a known behavior in complex corner cases. There are multiple other timezone libraries with different tradeoffs (e.g., correctness vs. easy-of-use vs. performance). Now, having the tz (zoneinfo) library right in the stdlib is wonderful and if it works for your use case, use it. – jfs Jul 24 '21 at 09:36
  • 1
    `If it doesn't return the expected time then it means that your computer is misconfigured`. What is the program is hosted on some remote server? In that case, won't `datetime.now()` give local time of the remote server? – Jdeep Dec 21 '21 at 03:23
  • 1
    @Jdeep: naturally, "local" refers to the computer where the code runs. – jfs Dec 21 '21 at 16:35
  • What if I don't know the users timezone. How do I get it then? – AnonymousUser Oct 17 '22 at 06:12
  • 1
    https://pypi.org/project/pytz/, PYTZ is not deprecated, the last release was on October 31, 2022. – Taylor D Nov 28 '22 at 18:11