4

I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first.

How do I do this? I can't find any resources that show the date in that format? Thank you.

2 Answers 2

12

You need the strptime method. If you're on Python 2.5 or higher, this is a method on datetime, otherwise you have to use a combination of the time and datetime modules to achieve this.

Python 2.5 up:

from datetime import datetime
dt = datetime.strptime(s, "%d/%m/%Y-%H:%M:%S")

below 2.5:

from datetime import datetime
from time import strptime
dt = datetime(*strptime(s, "%d/%m/%Y-%H:%M:%S")[0:6])
Sign up to request clarification or add additional context in comments.

2 Comments

Still get an error? :S >>> >>> time1 = "08-05-2009-05-10-54" >>> dt = datetime.strptime(time1, "%d-%m-%Y %H:%M:%S") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/_strptime.py", line 331, in strptime (data_string, format)) ValueError: time data did not match format: data=08-05-2009-05-10-54 fmt=%d-%m-%Y %H:%M:%S >>>
Actually, that was my fault! Thank you very much!
2

You can use the time.strptime() method to parse a date string. This will return a time_struct that you can pass to time.mktime() (when the string represents a local time) or calendar.timegm() (when the string is a UTC time) to get the number of seconds since the epoch.

Comments

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.