1

I've got a python string like this "2012/04/08 13:31:00 UTC" How can I convert it to a datetime object?

1
  • @Jakob Bowyer I read in the manual about striptime thinking it would work but it seemed difficult for me to use. Now I see how to do it. Thank you for the comment. Commented Apr 15, 2012 at 14:48

2 Answers 2

4

Use datetime.strptime.

from datetime import datetime
datetime.strptime("2012/04/08 13:31:00 UTC", "%Y/%m/%d %H:%M:%S %Z")

returns the datetime object:

datetime.datetime(2012, 4, 8, 13, 31)
Sign up to request clarification or add additional context in comments.

Comments

2

How about this?

from dateutil.parser import parse
parse('2012/04/08 13:31:00 UTC')

gives

datetime.datetime(2012, 4, 8, 13, 31, tzinfo=tzutc())

2 Comments

It's worth noting that dateutil is not a standard library, and thus could limit the portability. (Although it is great for the job..)
@Tim Good point, and worth pointing out - thanks. This just fits and is easy to use)

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.