1

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
mrgou
  • 1,576
  • 2
  • 21
  • 45

2 Answers2

1

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

andreihondrari
  • 5,743
  • 5
  • 30
  • 59
  • Right, but I don't want to specify a timezone. I want to print the computer's current timezone, whatever that is. – mrgou Apr 09 '19 at 11:30
1

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

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • So there's no solution with only the `datetime` module? – mrgou Apr 09 '19 at 11:41
  • basically there is one way, but not straight forward. you need to find the difference between the utc time and the local time, then you need to map the difference to the timezone and accordingly you can do, but the problem to such solution is you would not be able to distinguish when time zone is same for 2 countries, like india and sri lanka. – Arghya Saha Apr 09 '19 at 11:44