0

I have a data set consisting of time stamps looking as following:

['2019-12-18T12:06:55.697975Z"', '2019-12-18T12:06:55.707017Z"',...]

I need a for loop which will go through all timestamps and convert each to a time structure. But what I created, does not work - I am not sure about data types and also about indexing when using strings. My attempt is following:

from time import struct_time
for idx in enumerate(tm_str):   #tm_str is a string:['2019-12-18T12:06:55.697975Z"', ...]
    a=idx*30+2  #a should be first digit in year - third position in string - 
    b=idx*30+6  # b should last dgit of year, 30 is period to next year
    tm_year=tm_str[a:b]

Month, day, hour etc. should be done is similar way.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – mkrieger1 Jan 31 '20 at 21:49

1 Answers1

2

Have you tried the datetime library / datetime objects? https://docs.python.org/3/library/datetime.html

This will create datetime objects that you can use to do a lot of handy calculations.

from datetime import datetime

# your original list:
time_stamp_list = ['2019-12-18T12:06:55.697975Z"', '2019-12-18T12:06:55.707017Z"']

# empty list of datetime objects:
datetime_list = []

# iterate over each time_stamp in the original list:
for time_stamp in time_stamp_list:

    # convert to datetime object using datetime.strptime():
    datetime_object = datetime.strptime(time_stamp, '%Y-%m-%dT%H:%M:%S.%fZ"')

    # append datetime object to datetime object list:
    datetime_list.append(datetime_object)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Daniel
  • 3,228
  • 1
  • 7
  • 23