2

If I have a string of timestamp, is there some python library that can identify the format of timestamp and give me a datetime object? Example of a string is:

Sat, 16 Jan 2016 07:50:17 GMT

Can you also give an example of how it can be done?

2 Answers 2

6

Use dateutil. You can install it with pip.

from dateutil.parser import parse
dt = parse('Sat, 16 Jan 2016 07:50:17 GMT')
print(dt)
print(type(dt))

Output

2016-01-16 07:50:17+00:00
<type 'datetime.datetime'>
Sign up to request clarification or add additional context in comments.

4 Comments

For what it's worth, the package you have to install is "python-dateutil"
Hi. I was wondering if there was a way to obtain the format as a string, based on the input datetime value. For example: input value = 1978-07-06 output value = '%Y-%m-%d'
@TanviP: I think that you should search to see if a similar question has already been asked and, if you can't find one, ask it as a separate question. Perhaps looking at the dateutils source code might help.
@mhawke looked it up and couldn't find an answer. Asked a separate question (stackoverflow.com/questions/50893955/…) but couldn't find an answer there either. Tried using the dateinfer package, but no luck. Could use some help here.
1

You can use strptime() for parsing the string to a datetime type object.

from datetime import datetime
date_str = "Sat, 16 Jan 2016 07:50:17 GMT"
date_obj = datetime.strptime(date_str, '%a, %d %b %Y %X %Z')
print type(date_obj)

Output:

<type 'datetime.datetime'>

2 Comments

But it won't automatically identify the format of timestamp
yes. I think I misunderstood your question. You can follow mhawke's answer. I shall keep the answer as it shows another way of doing the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.