简体   繁体   English

在python 3.6中将不同的日期字符串转换为unix时间戳

[英]Convert different date strings to unix timestamp in python 3.6

I have two strings. 我有两个字符串。 How can I convert them to UNIX timestamp (eg.: "1284101485")? 如何将它们转换为UNIX时间戳(例如:“1284101485”)? (Please observe that 1284101485 is not the correct answer for this case.) (请注意,1284101485不是本案的正确答案。)

I don't care about time zones as long as it is consistent. 只要它是一致的,我不关心时区。

string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'   
string_2_to_convert = '2019-06-25 13:53:58'

You can use dateparser 您可以使用dateparser

Install: 安装:

$ pip install dateparser

Sample code: 示例代码:

import dateparser
from time import mktime

string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'

datetime1 = dateparser.parse(string_1_to_convert)
datetime2 = dateparser.parse(string_2_to_convert)

unix_secs_1 = mktime(datetime1.timetuple())
unix_secs_2 = mktime(datetime2.timetuple())

print(unix_secs_1)
print(unix_secs_2)

Output: 输出:

1561492438.0
1561488838.0

The above implementation gives you a consistent response and doesn't give you an error when trying to parse CEST . 上面的实现为您提供了一致的响应,并且在尝试解析CEST时没有给出错误。

you can use .strptime to parse by a format you specify. 您可以使用.strptime按您指定的格式进行解析。

try this: 尝试这个:

import datetime

string_1_to_convert = 'Tue Jun 25 13:53:58 CEST 2019'
string_2_to_convert = '2019-06-25 13:53:58'

ts1 = datetime.datetime.strptime(string_1_to_convert, "%a %b %d %H:%M:%S %Z %Y").timestamp()
ts2 = datetime.datetime.strptime(string_2_to_convert, "%Y-%m-%d %H:%M:%S").timestamp()

print(ts1)
print(ts2)

NOTICE: the CEST part might be non-portable, as strptime only knows how to parse timezones that appear in time.tzname . 注意: CEST部分可能是不可移植的,因为strptime只知道如何解析time.tzname中出现的时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM