1

How can I print current date/time formatted in a way which include correct timezone indication? I read datetime format mini-language here and so I've simply tried:

>>> '{:%Y-%m-%d %H:%M:%S %z}'.format(datetime.now())
'2014-10-04 20:33:07 '

But as you can see timezone is not printed. My locale is it-IT, hours/minutes is correct, so I expected %z to print +0200.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86

1 Answers1

3

You need to use datetime.astimezone(tz) Refer below;-

from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal

utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00
Community
  • 1
  • 1
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
  • Ok, so... In Python this is possible only with additional modules?!? – lorenzo-s Oct 04 '14 at 19:04
  • to get the current time in the local timezone: `datetime.now(get_localzone())` – jfs Oct 04 '14 at 19:05
  • Yes lorenzo as sebastian mentioned – Hussain Shabbir Oct 04 '14 at 19:06
  • @lorenzo-s: [follow the related link that I've provided in the comment to your question](http://stackoverflow.com/q/3168096/4279), to find stdlib only solution (for the current time). – jfs Oct 04 '14 at 19:06
  • 1
    @lorenzo-s: to support arbitrary dates (not only now), you need the tz database such as provided by `pytz` module. There is [PEP-0431 that suggests adding the zoneinfo to stdlib](http://legacy.python.org/dev/peps/pep-0431/). – jfs Oct 04 '14 at 19:10