0

I have two string :

date = '2017-05-09'
time = '19:28'

How do I convert this to posix time ?

ChiseledAbs
  • 1,963
  • 6
  • 19
  • 33

2 Answers2

2

You may want to use the datetime library. Also, keep in mind that the two methods presented below expect local time.

With

>>> date = '2017-05-09'
>>> time_ = '19:28'


For 2.7.+ versions (may be lower versions also) of python, you first have to turn your string into a datetime object
>>> import datetime as dt
>>> date_object = dt.datetime.strptime('{d} {t}'.format(d=date, t=time_), 
                                       "%Y-%m-%d %H:%M")
>>> date_object
datetime.datetime(2017, 5, 9, 19, 28)

Note that I changed your variable time into time_, so as not to create conflicts of name afterward. Getting a posix time is easy to do with date_object

>>> import time
>>> time.mktime(date_object.timetuple())
1494350880.0 #Given my local time !


For 3.+ versions of python, it is even more direct than above
>>> import datetime as dt
>>> dt.datetime.strptime('{d} {t}'.format(d=date, t=time_), 
                         '%Y-%m-%d %H:%M').timestamp()
1494350880.0 #Given my local time !
keepAlive
  • 6,369
  • 5
  • 24
  • 39
2

You can process as follow:

Convert the string date and time to datetime.datetime instance. Convert this instance to posix time:

import datetime
import time

my_date = '2017-05-09'
my_time = '19:28'

dt = datetime.datetime.strptime(my_date + " " + my_time, "%Y-%m-%d %H:%M")
posix_dt = time.mktime(dt.timetuple())
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103