0

I would like to convert two lists of strings into lists with one same time format.

Here are our two lists:

# first list: strings with UTC format
firstlist = ['2013-08-16T07:35:01Z','2012-11-17T17:07:49Z','2012-11-09T23:24:13Z']

# second list: strings with day-month-year format
secondlist = ['04-06-2016','31-10-2018','12-04-2019']

I would like to convert these two lists and get the same format year-month-day for each item:

['2013-08-16','2012-11-17','2012-11-09'] # expected for the first list
['2016-06-04','2018-10-31','2019-04-12'] # expected for the second list

I tried with just one item per list:

import time

time.strptime("2013-08-16T07:35:01Z", "%d %m %y")
time.strptime("04-06-2016", "%d %m %y")

But I get an error:

ValueError: time data '2013-08-16T07:35:01Z' does not match format '%d %m %y'

I found these two documentations: time and datetime.

But I am still really confused. There is probably something wrong with my method, but I struggle to find the right one for this case.

Filip Dimitrovski
  • 1,576
  • 11
  • 15
RobZ
  • 496
  • 1
  • 10
  • 26

3 Answers3

2

This does it


import dateutil.parser

firstlist = list (map (lambda x: str (dateutil.parser.parse (x).date()), firstlist))
secondlist = list (map (lambda x: str (dateutil.parser.parse (x).date()), secondlist))

Use dateutil.parser.parse to convert to datetime.

Source: here

hingev
  • 254
  • 1
  • 2
  • 7
2

strptime returns a struct_time object, given a string to parse. You need to specify the date/time format of the actual input string:

import time

# string to time struct
a = time.strptime("2013-08-16T07:35:01Z", "%Y-%m-%dT%H:%M:%SZ")
b = time.strptime("04-06-2016", "%d-%m-%Y")

Then, use strftime to format the struct_time object into a string:

# time struct to formatted string
a_formatted = time.strftime('%Y-%m-%d', a)
b_formatted = time.strftime('%Y-%m-%d', b)

print(a_formatted,b_formatted)

Output:

2013-08-16 2016-06-04
glhr
  • 4,439
  • 1
  • 15
  • 26
1

You can use dateutil parser to parse almost any time format.

import datetime
from dateutil.parser import parse


firstlist = ['2013-08-16T07:35:01Z','2012-11-17T17:07:49Z','2012-11-09T23:24:13Z']
secondlist = ['04-06-2016','31-10-2018','12-04-2019']

new_firstlist = [datetime.datetime.strftime(parse(dt), "%Y-%m-%d") for dt in firstlist]
new_secondlist = [datetime.datetime.strftime(parse(dt), "%Y-%m-%d") for dt in secondlist]

print(new_firstlist)
print(new_secondlist)