简体   繁体   English

如何将字符串转换为TimeStamps进行比较?

[英]How to convert strings to TimeStamps for compare?

I have strings like: 我有一些字符串:

first = '2018-09-16 15:00:00'

second = '1900-01-01 09:45:55.500597'

I want to compare them. 我想比较一下。

All methods I found like Convert string date to timestamp in Python requires to know the format of the string. 我发现的所有方法,如将字符串转换为Python中的时间戳,都需要知道字符串的格式。

I don't know the format of the strings (see differences between first and second ) all I know is that they can be converted to timestamps. 我不知道字符串的格式(请参阅firstsecond之间的差异)我所知道的是它们可以转换为时间戳。

How can I convert them in order to compare them? 我如何转换它们以便比较它们?

Edit: The "largest" string that I can get is: 编辑:我能得到的“最大”字符串是:

1900-01-01 09:45:55.500597

but I can also get: 但我也可以得到:

1900-01-01
1900-01-01 09:45
1900-01-01 09:45:55

etc.. 等等..

It's always YYYY-MM-DD HH-MM.... 总是YYYY-MM-DD HH-MM....

You can use the dateutil module ( pip install python-dateutil ): 您可以使用dateutil模块( pip install python-dateutil ):

>>> from dateutil.parser import parse
>>> parse('2018-09-16 15:00:00')
datetime.datetime(2018, 9, 16, 15, 0)
>>> parse('1900-01-01 09:45:55.500597')
datetime.datetime(1900, 1, 1, 9, 45, 55, 500597)

From the list of its features : 从其功能列表:

Generic parsing of dates in almost any string format; 以几乎任何字符串格式对日期进行通用解析;

Once you have the datetime objects, you can compare them directly, there's no need to calculate the timestamps. 获得datetime对象后,可以直接比较它们,无需计算时间戳。

You can use pandas.to_datetime . 您可以使用pandas.to_datetime It offers a lot of flexibility in the string timestamp format, and you can use it on single strings or list/series/tuples of timestamps. 它在字符串时间戳格式中提供了很大的灵活性,您可以在单个字符串或列表/系列/元组的时间戳上使用它。

>>> import pandas as pd
>>> day = pd.to_datetime('1900-01-01')
>>> minute = pd.to_datetime('1900-01-01 09:45')
>>> second = pd.to_datetime('1900-01-01 09:45:55')
>>> subsecond = pd.to_datetime('1900-01-01 09:45:55.500597')
>>> assert subsecond > second 
>>> assert minute < second 
>>> assert day < minute 

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

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