1

In Python 3.x, I want to capture current time along with its timezone and then convert it into Unix timestamp and sent to a server.

I have tried various libraries like pytz, arrow, moment, pendulum, but I am not sure how to deal with daylight saving time (DST). Currently, I am using time.tzname to get timezone information but it specifically showing India in DST. In reality India never follows DST.

B--rian
  • 5,578
  • 10
  • 38
  • 89
Adataguy
  • 25
  • 6
  • 2
    Welcome to SO! Please also add some minimal code snippet. – B--rian Aug 08 '19 at 12:52
  • Unix timestamps are always UTC based. Thus, if you just want the current time as a Unix timestamp, just get the current UTC time directly. No need to involve time zones or DST. See https://stackoverflow.com/q/16755394/634824 – Matt Johnson-Pint Aug 09 '19 at 14:10

2 Answers2

1

The library pytz should work pretty well. You need to use the function dst() from that library to check if a timezone is under daylight savings influence.

https://medium.com/@nqbao/python-timezone-and-daylight-savings-e511a0093d0

From the link above:

>>> import pytz
>>> pst = pytz.timezone("US/Pacific")
>>> pst.localize(datetime(2017, 10, 1)).dst()
datetime.timedelta(0, 3600)
>>> pst.localize(datetime(2017, 12, 1)).dst()
datetime.timedelta(0)

Understanding offset naive and offset aware date times will make your life much easier.

Csaba Németh
  • 33
  • 1
  • 5
  • @Csaba_Nemeth Thanks for your input. Please edit your answer and quote the essential parts from the website you cited. It might also help, if you add a minimal working code snippet. – B--rian Aug 09 '19 at 08:30
0

This helped me in resolving the issue using time.tzname

    if time.tzname[1] is None or time.tzname[0] == time.tzname[1]:
        timezone = time.localtime().tm_zone
            # no DST
            timezone = time.tzname[0]
        else:

            # we're in DST
            timezone = time.tzname[1]
Adataguy
  • 25
  • 6