2

I'm trying to calculate average time distance from a point to another. This is the functions for the import data.

While handling the time there is an error about the type list of the start time

stime_record :

[['01/01/2016 00h15m'], ['01/01/2016 00h48m'], ['01/01/2016 01h08m'], ['01/01/2016 03h06m'], ['01/01/2016 05h22m'], ['01/01/2016 08h34m'], ['01/01/2016 09h59m']]

func :

for x in stime_record:
    datetime.strptime(str(x), '%d/%m/%Y %Hh%Mm')

ValueError: time data "['01/01/2016 00h15m']" does not match format '%d/%m/%Y %Hh%Mm'
jpp
  • 159,742
  • 34
  • 281
  • 339
DeboraID
  • 39
  • 5

2 Answers2

1

Simply just try this:

datetime.strptime(str(x[0]), '%d/%m/%Y %Hh%Mm')

This is why you have a list of lists so in each iteration the x will be a list not string, and when you convert it to str, it is not going to match.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

You have a list of lists here, not a list of strings. One way to deal with the issue is to flatten before processing. A list comprehension with itertools.chain is an efficient way to do this.

from datetime import datetime
from itertools import chain

lst = [['01/01/2016 00h15m'], ['01/01/2016 00h48m'], ['01/01/2016 01h08m'],
       ['01/01/2016 03h06m'], ['01/01/2016 05h22m'], ['01/01/2016 08h34m'],
       ['01/01/2016 09h59m']]

res = [datetime.strptime(x, '%d/%m/%Y %Hh%Mm') for x in chain.from_iterable(lst)]

print(res)

[datetime.datetime(2016, 1, 1, 0, 15), datetime.datetime(2016, 1, 1, 0, 48),
 datetime.datetime(2016, 1, 1, 1, 8), datetime.datetime(2016, 1, 1, 3, 6),
 datetime.datetime(2016, 1, 1, 5, 22), datetime.datetime(2016, 1, 1, 8, 34),
 datetime.datetime(2016, 1, 1, 9, 59)]

If you wish to iterate results without forming a new list, use a generator expression:

for dt in (datetime.strptime(x, '%d/%m/%Y %Hh%Mm') for x in chain.from_iterable(lst)):
    # do something with dt
jpp
  • 159,742
  • 34
  • 281
  • 339