5

I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14.

Scenario: user signs up and I want to count down the number of days remaining in their trial.

user299709
  • 4,922
  • 10
  • 56
  • 88
  • 2
    One thing: pretty sure `245293529385` is not the correct timestamp, since it refers to "Wed, 16 Jan 9743 11:29:45 GMT" ;) – michaelb Oct 01 '14 at 01:45

2 Answers2

6

time.strptime to the rescue! Use the format string %Y-%m-%d %H:%M:%S.%f. For example:

   import time
   t = '2014-08-14 20:01:28.242'
   ts = time.strptime(t, '%Y-%m-%d  %H:%M:%S.%f')
   timestamp = time.mktime(ts)

Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ):

   from datetime import datetime
   dt = datetime.fromtimestamp(timestamp)
Community
  • 1
  • 1
michaelb
  • 747
  • 3
  • 9
  • you could also do all this with `datetime`, without having to first deal with `time` at all... – MattDMo Oct 01 '14 at 01:35
  • `%f` means `Microsecond as a decimal number, zero-padded on the left. 000000, 000001, ..., 999999` right? [Here](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior) – B.Mr.W. Oct 01 '14 at 01:36
  • @B.Mr.W. The 4th note [here](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior): "%f is an extension to the set of format characters in the C standard [...] When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right." So it accepts any number of characters. – michaelb Oct 01 '14 at 01:38
  • @user299709 thats a different issue, why don't you accept this answer, and post your update as a new separate question? – michaelb Oct 01 '14 at 14:57
  • both `mktime()` and `fromtimestamp()` may fail for some dates on some systems. And they are not necessary, [use `datetime.strptime()` directly instead.](http://stackoverflow.com/a/26132778/4279) – jfs Sep 22 '15 at 23:38
  • great answer! however mind that datetime object cares about timezones :) ("naive","aware" objects, etc..) – José Crespo Barrios Jun 30 '20 at 09:44
2

There are two parts:

Convert input time string into datetime object

#!/usr/bin/env python
from datetime import datetime

dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d  %H:%M:%S.%f')

Convert datetime object to Unix time ("seconds since epoch")

The result depends on what time zone is used for the input time e.g., if the input is in UTC then the corresponding POSIX timestamp is:

timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242

If your input is in the local timezone then see How do I convert local time to UTC in Python?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670