-1

I need to convert a list in seconds in Python. The list is the following:

[27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]

That are day, month, year, hours, minutes, seconds.

I tried to use datetime.strptime after converting it in a string, but it returns the error ValueError: time data '...' does not match format...

Kitama
  • 21
  • 1
  • 4
  • Show the desired result and your code. – timgeb May 13 '20 at 10:58
  • 1
    The title is missleading; this has nothing to do with `strptime`. It should be something like "how to create a datetime object from a list". How to get seconds since the epoch can be found e.g. [here](https://stackoverflow.com/questions/7852855/in-python-how-do-you-convert-a-datetime-object-to-seconds). – FObersteiner May 13 '20 at 12:22

2 Answers2

1

Using datetime but parsing the fields

Fields must be int (so convert from float)

from datetime import datetime

d = [27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]

date = datetime(year = int(d[2]), month = int(d[1]), day=int(d[0]),
             hour = int(d[3]), minute = int(d[4]), second=int(d[5]),
             microsecond= int(1e6*(d[5]-int(d[5]))))

print(date)
# Output: 2019-02-27 19:59:59.990000

print((date-datetime(1970,1,1)).total_seconds()) # Seconds since Jan 1, 1970
                                                 # i.e. Unix time in seconds
# Output: 1551297599.99
DarrylG
  • 16,732
  • 2
  • 17
  • 23
0

You can try datetime package in python as below

import datetime
l = [27.0, 2.0, 2019.0, 19.0, 59.0, 59.99]
l_int = list(map(int,l))

d = datetime.datetime(l_int[2],l_int[1],l_int[0], l_int[3], l_int[4],l_int[5])
print(d)

#2019-02-27 19:59:59