My input is input_time = "May 5 2016 11:29:32". Expected output should be in seconds or milli seconds which is type of integer i.e., output_time = 2424241313113. The above conversion should be done in python. How to do this conversion?
1 Answer
Here's how to convert date time into epoch seconds (dated starting from 00:00:00 UTC on 1 January 1970)
In Python 3.3+
from datetime import datetime
datetime.strptime('May 5 2016 11:29:32','%b %d %Y %H:%M:%S').timestamp()
In Python 2.7.9
datetime.strptime('May 5 2016 11:29:32','%b %d %Y %H:%M:%S').strftime('%s')
Note that strftime('%s') use your local time zone.
6 Comments
user27
Could you tell me, the value returns is in secs or in milli secs?
user27
If the value getting in negative value, what does it meant for?
jfs
.strftime('%s') is not supported by Python and it is not portable. If the input is the local time then time.mktime(dt.timetuple()) could be used. mktime() and .timestamp() that uses it may fail if python has no access to a historical timezone database on a given platform or if the input time is ambiguous or non-existent in the local timezone.jamesw1234
@user27 the value is seconds
jamesw1234
can you give example of when the value is negative? If you try to convert a datetime before 1970, like
datetime.strptime('May 5 1016 11:29:32','%b %d %Y %H:%M:%S').timestamp() it returns OverflowError: timestamp out of range |
datetimeyet?datetimemodule. More specifically,strptime().