0

I have a variable 'd' that contains dates in this format:

2015-08-03T09:00:00-07:00
2015-08-03T10:00:00-07:00
2015-08-03T11:00:00-07:00
2015-08-03T12:00:00-07:00
2015-08-03T13:00:00-07:00
2015-08-03T14:00:00-07:00

etc.

I need to strip these dates, but I'm having trouble because of the timezone. If I use d = dt.datetime.strptime(d[:19],'%Y-%m-%dT%H:%M:%S'), only the first 19 characters will appear and the rest of the dates are ignored. If I try d = dt.datetime.strptime(d[:-6],'%Y-%m-%dT%H:%M:%S, Python doesn't chop off the timezone and I still get the error ValueError: unconverted data remains: -07:00. I don't think I can use the dateutil parser because I've only seen it be used for one date instead of a whole list like I have. What can I do? Thanks!

sfischer3394
  • 79
  • 10

1 Answers1

2

Since you have a list just iterate over and use dateutil.parser:

d = ["2015-08-03T09:00:00-07:00","2015-08-03T10:00:00-07:00","2015-08-03T11:00:00-07:00","2015-08-03T12:00:00-07:00",
     "2015-08-03T13:00:00-07:00","2015-08-03T14:00:00-07:00"]

from dateutil import parser

for dte in d:
    print(parser.parse(dte))

If for some reason you actually want to ignore the timezone you can use rsplit with datetime.strptime:

from datetime import datetime

for dte in d:
    print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S"))

If you had a single string delimited by commas then just use d.split(",")

You can use strftime to format the string in any format you want if you actually want a string:

for dte in d:
    print(datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S").strftime("%Y-%m-%d %H:%M:%S"))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321