简体   繁体   中英

Extract timestamp from a given string using python

I tried multiple packages to extract timestamp from a given string, but no package gives correct results. I did use dateutils , datefinder , parsedatetime , etc. for this task. They extract some datetimes which are in certain formats but not all formats, sometimes they extract some unwanted numbers also as timestamps.

Is there any python package which extracts datetime from a given string.

Assume, I have 2 strings like these:

scala> val xorder= new order(1,"2016-02-22 00:00:00.00",100,"COMPLETED") 

and

Fri, 10 Jun 2011 11:04:17 +0200 (CEST)

and want to extract only datetime . Is there any function which extracts both formats of datetimes from above strings. In other cases formats may be different, still it should pick out datetime strings

You can use the datetime function strptime() as follows

dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")

You can create your own formatting and use the function as well.

I created a small python package datetime_extractor to pull out timestamps from a given strings. It can extract many datetime formats from given strings. Hope it will be useful.

pip install datetime-extractor

from datetime_extractor import DateTimeExtractor
import re

samplestring1 = 'scala> val xorder= new order(1,"2016-02-22 00:00:00.00",100,"COMPLETED")'

DateTimeExtractor(samplestring1)

Out: ['2016-02-22 00:00:00.00']

samplestring2 = 'Fri, 10 Jun 2011 11:04:17 +0200 (CEST)'

DateTimeExtractor(samplestring2)

Out: ['10 Jun 2011 11:04:17']

@Allan & @Manmeet Singh, Let me know your comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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