Reputation: 45
I'm trying to parse a datetime object from a cell in MS excel, I have successfully done this with alternative time formats but strptime()
seems to have difficulty with this one format.
I've printed the cell value, which is correct, I have another operation which processes a similar field but without the time and tz information which works.
Code snippet:
report_date = datetime.strptime(gs_df_vars.iloc[2, 1], '%b %d, %Y').strftime('%d/%m/%Y') # Works just fine
print(report_date)
print(gs_df_vars.iloc[3, 1])
run_date = datetime.strptime(gs_df_vars.iloc[3, 1], '%b %d, %Y %I:%M %p %Z').strftime('%d/%m/%Y') # Does not work just fine at all
raises
ValueError: time data 'Jun 14, 2019 02:42 AM EDT' does not match format '%b %d, %Y %I:%M %p %Z'
where gs_df_vars.iloc[3, 1] == 'Jun 14, 2019 02:42 AM EDT'
Maybe I'm missing something here, but I expect it to just work... Perhaps strptime()
can't deal with EDT timezone?
Upvotes: 1
Views: 102
Reputation: 2497
That probably won't work because those abbreviations aren't unique. You might wind up just having to manually handle it yourself if you're working with a known set of inputs. See https://www.timeanddate.com/time/zones/ for more info
If you can pass a dict of timezone abbreviation and corresponding dict. It should work.
from dateutil import tz
from dateutil.parser import parse
ET = tz.gettz('US/Eastern')
CT = tz.gettz('US/Central')
MT = tz.gettz('US/Mountain')
PT = tz.gettz('US/Pacific')
us_tzinfos = {'CST': CT, 'CDT': CT,
'EST': ET, 'EDT': ET,
'MST': MT, 'MDT': MT,
'PST': PT, 'PDT': PT}
dt_est = parse('2014-01-02 04:00:00 EST', tzinfos=us_tzinfos)
dt_pst = parse('2016-03-11 16:00:00 PST', tzinfos=us_tzinfos)
Upvotes: 2