tags:

views:

393

answers:

2

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.

A: 

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.

Steef
+6  A: 

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])
Daniel Roseman
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>>>
day_trader
Actually, that was my fault! Thank you very much!
day_trader