1

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?

2
  • Have you looked at datetime yet? Commented May 5, 2016 at 6:17
  • As Ignacio mentioned, check out the datetime module. More specifically, strptime(). Commented May 5, 2016 at 6:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Could you tell me, the value returns is in secs or in milli secs?
If the value getting in negative value, what does it meant for?
.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.
@user27 the value is seconds
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.