简体   繁体   English

如何将日期时间转换为 python 中的 unix 时间戳

[英]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.

相关问题 在Python中将日期时间转换为Unix时间戳 - Convert datetime to unix timestamp in python 将 datetime 转换为 Unix 时间戳并将其转换回 python - Convert datetime to Unix timestamp and convert it back in python 如何使用python将Unix时间戳转换为DateTime,反之亦然? - How to convert a Unix timestamp to DateTime and vice versa with python? 如何从 IntgerField(Timestamp) 转换为 python 日期时间 - How can i convert from IntgerField(Timestamp) to python datetime 如何从python datetime中的当前时间获取unix时间戳x秒? - How can I get a unix timestamp x seconds from the current time in python datetime? 如何将多个Unix时间戳转换为Pandas日期时间? - How to Convert Multiple Unix TimeStamp to Pandas Datetime? 如何在 Python 中将日期时间对象转换为自纪元(unix 时间)以来的毫秒数? - How can I convert a datetime object to milliseconds since epoch (unix time) in Python? 尝试在python 2.7中将datetime转换为unix时间戳时发生属性错误 - attribute error while trying to convert datetime to unix timestamp in python 2.7 将Python中的unix时间戳转换为日期时间,并使2小时后退 - Convert unix timestamp in Python to datetime and make 2 Hours behind 将特定时区的日期时间转换为 python 中的 unix 时间戳 - Convert datetime from a specific timezone into unix timestamp in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM