2

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.

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.

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....

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
Programmer120
  • 2,362
  • 9
  • 30
  • 48
  • The only difference i see is the milisseconds on the second one, if this is the only difference, you should be able to assume the same format for everything if you get the same amount of characters per string. Unless there's a dramatical change from one to another (yyyy-mm-dd, to dd-mm-yyyy) – Rodolfo Donã Hosp Sep 17 '18 at 15:27
  • You'll either have to have several goes at guessing the format (presumably it's one of a handful) or you could use something like [`dateparser`](https://pypi.org/project/dateparser/) but that will add overhead – roganjosh Sep 17 '18 at 15:27
  • Possible duplicate of [Convert "unknown format" strings to datetime objects?](https://stackoverflow.com/questions/13258554/convert-unknown-format-strings-to-datetime-objects) – roganjosh Sep 17 '18 at 15:30
  • @RodolfoDonãHosp format will always be YYYY-MM-DD I just don't know what comes after... if I'll have hours and minutes or not. `second` is the "full" one. – Programmer120 Sep 17 '18 at 15:30

2 Answers2

2

You can use the dateutil module (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.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

You can use 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 
PabTorre
  • 2,878
  • 21
  • 30