[Python] Convert a time stamp to seconds from an epoch

Discussão em 'Python' iniciado por Stack, Abril 9, 2025.

  1. Stack

    Stack Membro Participativo

    I have found this Python function that converts my timestamp into an epoch:

    def str_to_timestamp(timestr, epoch=dt.datetime.fromtimestamp(0)):
    stamp = dt.datetime.strptime(timestr.strip()[0:20], '%Y-%m-%d %H:%M:%S')
    return (stamp - epoch).total_seconds()


    However, this gives a 1 hour error during summer time (daylight savings). How do I modify the function so it uses local time please?

    The hour error is that the epoch seconds returned is for UTC, not my local time in London time zone as we're now on British Summer Time since 30th March, 1 hour ahead, so it's 3600 seconds less than it should be for my local time. That's what I need to fix somehow? TIA.

    i.e. This date & time converts OK, "2025-03-29 23:06:24" and gives me the seconds I want as it was before the clocks in the UK went forward on 30th March 2025. However this date & time "2025-03-30 09:54:07" converts to seconds that is 3600 too small since we're now in British Summer time, one hour ahead. I need something that recognises we are in British summer time and converts to seconds from epoch accordingly, but still works when we're in GMT/UTC.

    I guess I need Python to know what my local time zone IS, and give me the seconds from epoch for MY local time, not UTC.

    So, this is where I'm getting confused:

    def str_to_timestamp(timestr, epoch=dt.datetime.fromtimestamp(0)):
    stamp = dt.datetime.strptime(timestr.strip()[0:20], '%Y-%m-%d %H:%M:%S')
    return (stamp - epoch).total_seconds()

    t1 = "2025-03-29 12:00:00"
    t2 = "2025-03-30 12:00:00"
    print(str_to_timestamp(t2)-str_to_timestamp(t1))
    86400.0


    BUT, since the clocks went forward one hour between 29th & 30th March, I expect the difference to be 82800 seconds, i.e. one hour less. I think I need to set my local time zone to "Europe/London" before the conversion, or as part of the function somehow?

    Continue reading...

Compartilhe esta Página