如何在Python中将日期时间转换为unix时间戳

问题描述 投票:0回答:1

我有一种日期格式“Mon, 15 Jun 2020 22:11:06 PT”我想将此格式转换为unix时间戳。

我正在使用以下代码===>

news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())   

但是出现以下错误===>

ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'

我该如何解决它并从中获取unix时间戳?

python datetime unix timestamp
1个回答
3
投票

2024年编辑:

  • 一般注意事项:使用Python 3.9+,使用zoneinfo。不再需要第 3 方库。
  • dateutil 特定: dateutil 的解析器可以输入缩写到 IANA 时区名称的映射,以解析缩写。 示例

2020年答案:

%Z
无法解析时区缩写
PT
- 我建议您跳过解析它并“手动”添加它:

from datetime import datetime
import dateutil

news_date = "Mon, 15 Jun 2020 22:11:06 PT"

# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')

# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))

# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0

如果您有多个具有不同时区的字符串,您可以使用

dict
将缩写映射到 时区名称,例如

tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)
© www.soinside.com 2019 - 2024. All rights reserved.