Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: convert date timestamp to epoch unix time and figure out number of days remaining?

Tags:

python

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.

like image 912
user299709 Avatar asked Mar 19 '23 08:03

user299709


2 Answers

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)
like image 154
michaelb Avatar answered May 02 '23 11:05

michaelb


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?

like image 39
jfs Avatar answered May 02 '23 11:05

jfs