[python] Python get current time in right timezone

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?

This question is related to python time timezone

The answer is


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.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST