mrgou
mrgou

Reputation: 2458

Display timezone name in formatted datetime string

I want to print the current date and time, with the timezone name, for the local machine. However, I can't seem to get the last bit

In [1]: from datetime import datetime

In [2]: print(datetime.now().strftime('%d %b %Y %H:%M:%S'))
09 Apr 2019 13:23:47

In [3]: print(datetime.now().strftime('%d %b %Y %H:%M:%S %Z'))
09 Apr 2019 13:23:52

I would have expected to see my PC's timezone name ('CET') added to the second string. How do I get:

09 Apr 2019 13:23:52 CET

Upvotes: 1

Views: 247

Answers (2)

Arghya Saha
Arghya Saha

Reputation: 5713

Basically if you want timezone info of your system use time library.

>>> import time
>>> time.tzname
('IST', 'IST')

In my case the timezone is IST.

Update If you want to use only datetime module there is a hacky way but definitely not recommended. The solution is mention in this answer. But again the problem is, it is not full proof, suppose you have same timezone difference for 2 countries like India and Sri lanka, then it would fail to recognise the correct one, since IST and SLST both are GMT+5:30

Upvotes: 1

andreihondrari
andreihondrari

Reputation: 5833

That's because datetime.now's default tz argument is None.

Example of how to specify the timezone:

from pytz import UTC
datetime.now(tz=UTC).strftime("%Z")

spits UTC.

If you want to get your current timezone then:

import time
time.strftime("%Z", time.gmtime())

In my case it's GMT

Upvotes: 1

Related Questions