[英]How can I convert datetime to unix timestamp in python
I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.我有一种日期格式“星期一,2020 年 6 月 15 日 22:11:06 PT”我想将此格式转换为 unix 时间戳。
I am using the following code ===>我正在使用以下代码 ===>
news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())
But gives the following error ===>但是给出以下错误===>
ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
How can i solve it and get the unix timestamp from this?我该如何解决它并从中获取 unix 时间戳?
%Z
can't parse the timezone name PT
- I suggest you skip parsing it and add it "manually" instead: %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
if you have multiple strings with different timezones, you could use a dict
to map the abbreviations to time zone names , eg如果您有多个具有不同时区的字符串,您可以使用dict
map时区名称的缩写,例如
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.