Python 日期时间转换

Python datetime conversion

import datetime as dt
from dateutil.tz import gettz
import time

timezone_a = "Japan"
timezone_b = "Europe/London"
unix_time = 1619238722

result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_a)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_a)
result = dt.datetime.fromtimestamp(unix_time, gettz(timezone_b)).strftime("%Y-%m-%d-%H-%M-%S")
print(result, timezone_b)

# This code prints
""" 
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London

I am trying to reverse it backwards so that input is
2021-04-24-13-32-02 Japan
2021-04-24-05-32-02 Europe/London


And output is 1619238722

"""

您好,我想弄清楚如何将带有时区的字符串转换为 Unix 时间。任何帮助将不胜感激。谢谢!

查看此代码是否有效。

# convert string to datetimeformat
date = datetime.datetime.strptime(date, "%Y-%m-%d-%H-%M-%S %Z")

# convert datetime to timestamp
unixtime = datetime.datetime.timestamp(date)

afaik,标准库中没有内置方法来解析 IANA 时区名称。但是你可以自己做,比如

from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+

t = ["2021-04-24-13-32-02 Japan", "2021-04-24-05-32-02 Europe/London"]

# split strings into tuples of date/time + time zone
t = [elem.rsplit(' ', 1) for elem in t]

# parse first element of the resulting tuples to datetime
# add time zone (second element from tuple)
# and take unix time
unix_t = [datetime.strptime(elem[0], "%Y-%m-%d-%H-%M-%S")
          .replace(tzinfo=ZoneInfo(elem[1]))
          .timestamp()
          for elem in t]

# unix_t
# [1619238722.0, 1619238722.0]