Search code examples
pythonpython-datetime

Get the local time without daylight savings applied, using the latest methodology


I am trying to get the local time without the application of daylight savings time.

I know that I can get the local time with the following, but when my location is in DST I get an extra hour. I want standard time all the time.

localTime = datetime.now()

My searches have found a lot of references to the pytz module. But there are references to using builtin functions and not to use pytz as of version 3.6 of python as it is deprecated.

What I am after is the correct way of doing this in version 3.11 of python.


Solution

  • Maybe this is what you are looking for:

    import datetime as dt
    import time
    
    # Dynamically fetch local standard time and build a fixed timezone.
    # time.timezone is the local time's number of seconds WEST of prime meridian (- for east).
    LST = dt.timezone(-dt.timedelta(seconds=time.timezone), 'LST')
    print(dt.datetime.now(tz=LST))  # I am in PST now (GMT-8)
    print()
    
    # Normally PST daylight time would be -07:00 April - November.
    for month in range(1, 13):
        print(dt.datetime(2024, month, 1, tzinfo=LST))
    

    Output:

    2024-01-18 16:11:12.090088-08:00
    
    2024-01-01 00:00:00-08:00
    2024-02-01 00:00:00-08:00
    2024-03-01 00:00:00-08:00
    2024-04-01 00:00:00-08:00
    2024-05-01 00:00:00-08:00
    2024-06-01 00:00:00-08:00
    2024-07-01 00:00:00-08:00
    2024-08-01 00:00:00-08:00
    2024-09-01 00:00:00-08:00
    2024-10-01 00:00:00-08:00
    2024-11-01 00:00:00-08:00
    2024-12-01 00:00:00-08:00