问题
I have string in next format: 2017-02-14T09:51:46.000-0600
What is the best approach to parse and convert string into timestamp? I have options to use regular expression or to write my own function for parsing, but are there any builtin methods which can help me?
回答1:
First part would be creating datetime object:
from datetime import datetime
date_string = "2017-02-14T09:51:46.000-0600"
# I'm using date_string[:-9] to skip ".000-0600"
format_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z'))
After which format date is:
print(format_date)
2017-02-14 09:51:46
And timestamp is:
print(format_date.timestamp())
1487062306.0
Little clarification here, on python reference page, you can see definition for '%Y-%m-%dT%H:%M:%S.%f%z')
format specifiers I used.
- %Y: Year with century as a decimal number, e.g. 1970, 1988, 2001, 2013
- %m: Month as a zero-padded decimal number (e.g. 01, 02, ..., 12)
- %d: Day of the month as a zero-padded decimal number (e.g. 01, 02, ..., 31)
- %H: Hour (24-hour clock) as a zero-padded decimal number (e.g 00, 01, ..., 23)
- %M: Minute as a zero-padded decimal number (e.g 00, 01, ..., 59)
- %S: Second as a zero-padded decimal number (e.g. 00, 01, ..., 59)
- %f: Microsecond as a decimal number, zero-padded on the left (000000, 000001, ..., 999999)
- %z: UTC offset in the form +HHMM or -HHMM, empty string if the the object is naive, (empty or +0000, -0400, +1030)
回答2:
Here is the code form where you can parse and convert string in timestamp
>>> import time
>>> import datetime
>>> s = "2017-02-14T09:51:46.000-0600"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
来源:https://stackoverflow.com/questions/44691220/python-parsing-and-converting-string-into-timestamp