JonathanG
JonathanG

Reputation: 292

Time format in python

I have a date that looks like this :

November 19th 2015, 12:48:34.402

And I need to figure out a way to convert it to a timestamp. I'm trying it this way but I can't find the right pattern to format it.

time.mktime(datetime.datetime.strptime(parsed["_timestamp"], "%B %d %Y, %H:%M:%S").timetuple())

Any suggestion on maybe how to get the right format?

Upvotes: 3

Views: 238

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49320

Your formatting string was a bit off. You need to include the th, rd, etc., the decimal point for the seconds, and the microseconds (which is %f). We'll find the proper th/etc. with a split():

>>> a = 'November 19th 2015, 12:48:34.402'
>>> time.mktime(datetime.datetime.strptime(a, "%B %d{} %Y, %H:%M:%S.%f".format(a.split()[1][-2:])).timetuple())
1447966114.0
>>> a = 'November 23rd 2015, 12:48:34.402'
>>> time.mktime(datetime.datetime.strptime(a, "%B %d{} %Y, %H:%M:%S.%f".format(a.split()[1][-2:])).timetuple())
1448311714.0

Upvotes: 5

numentar
numentar

Reputation: 1079

This should work:

import datetime
import time
timestring = "November 19th 2015, 12:48:34.402"
timeformat = "%B %dth %Y, %H:%M:%S.%f"
print int(time.mktime(datetime.datetime.strptime(timestring, timeformat)))
1447962514

If you're ok with using dateutil then you don't have to worry about the format much:

import dateutil.parser

timestamp = int(time.mktime(dateutil.parser.parse(timestring).timetuple()))
print timestamp
1447962514

Upvotes: 4

Related Questions