I want to know how to convert this date format
"Thu 21st Aug '14, 4:58am"
to a timestamp with Python?
Another format that I need to convert:
"Yesterday, 7:22am"
I tried parse util without success...
I want to know how to convert this date format
"Thu 21st Aug '14, 4:58am"
to a timestamp with Python?
Another format that I need to convert:
"Yesterday, 7:22am"
I tried parse util without success...
If you haven't done so already, have a look at the parse
function in dateutils.parser
for parsing strings representing dates...
>>> from dateutil.parser import parse
>>> dt = parse("Thu 21st Aug '14, 4:58am")
>>> dt
datetime.datetime(2014, 8, 21, 4, 58)
...and then to convert a datetime
object to a timestamp, you can do the following:
>>> import time
>>> import datetime
>>> time.mktime(dt.timetuple())
1408593480.0
As side remark, parse
is a useful function which can recognise a huge range of different date formats. However it's sometimes too helpful and sees dates where perhaps a date is not intended:
>>> parse("14, m 23")
datetime.datetime(2014, 8, 23, 0, 14)
If you also want to parse expressions such as "Yesterday, 7:22am", you could do one of two things:
Replace "yesterday", "yester-day", "yday" and other variations with "25/08/2014" (or another appropriate date) and then use parse
on the new string.
Use another library to parse the string. parsedatetime is one option...
Here's parsedatetime in action on your example:
>>> import parsedatetime.parsedatetime as pdt
>>> p = pdt.Calendar()
>>> d = p.parse("Yesterday, 7:22am")
>>> d
((2014, 8, 25, 7, 22, 0, 0, 237, -1), 3)
To turn this date representation d
into a datetime
object, you can unpack the tuple like so:
>>> dt = datetime.datetime(*d[0][:7])
>>> dt
datetime.datetime(2014, 8, 25, 7, 22)
Now dt
can be easily converted to a timestamp in the way described above.
You can use this:
a = "Thu 21st Aug '14, 4:58am"
datetime.datetime.strptime(a, '%a %dst %b \'%y, %H:%M%p')