Home > Mobile >  Convert string time with offset from UTC to UTC unix
Convert string time with offset from UTC to UTC unix

Time:06-29

How to convert string time with offset from UTC to UTC unix?

CodePudding user response:

Code:

from datetime import datetime, timezone, timedelta


def strtime_to_unix(str_time: str, utc_offset: int, format: str = '%d.%m.%Y %H:%M') -> int:
    return int(datetime.strptime(str_time, format).replace(
        tzinfo=timezone(timedelta(seconds=utc_offset * 60 * 60))).timestamp())


str_time = '27.06.2022 12:35'

print(strtime_to_unix(str_time, 0))  # 12:35 UTC -> 1656333300
print(strtime_to_unix(str_time, -4))  # 16:35 UTC -> 1656347700
print(strtime_to_unix(str_time, 3))  # 09:35 UTC -> 1656322500

Output:

1656333300
1656347700
1656322500
  • Related