Reputation: 105
I have the list of times posted below and am having difficulties with converting it to the following:
Step 1: Convert to EST time in 24-hour format.
Step 2: Convert to 12 hour EST time format.
I have tried doing this in both Python and Pandas and I'm willing to use whatever is easiest. Any help would be greatly appreciated.
['00:05', '17:07', '23:05', '23:05', '23:10', '23:10', '00:10', '00:15',
'00:40', '01:40', '02:10']
Upvotes: 2
Views: 4434
Reputation: 3783
We can easily achieve what you're looking for with datetime
:
>>> import datetime
>>> times = [ "08:00", "23:00" ]
>>> [datetime.datetime.strptime(time, "%H:%M").strftime("%I:%M %p") for time in times]
['08:00 AM', '11:00 PM']
This reads your time
in with strptime
and then outputs it with strftime
inside a list comprehension. To convert this to EST
with no daylight savings time (which is -05:00
) you can use pytz:
>>> import pytz
>>> [datetime.datetime.strptime(time, "%H:%M").replace(tzinfo=pytz.utc).astimezone(pytz.timezone('EST')).strftime("%I:%M %p") for time in times]
['03:00 AM', '06:00 PM']
Which first marks the time as utc
(replace(tzinfo=pytz.utc)
) and then converts it to EST astimezone(pytz.timezone('EST'))
before reformatting it to 12 hour time.
Going one step further to what I think you want, which is to get the time today in EDT
(EST
factoring in datetime
) we can take a hint from [this question][2]:
converted = []
tz = pytz.timezone('America/New_York')
for time in times:
time = datetime.datetime.strptime(time, "%H:%M").time()
converted.append(datetime.datetime.now(pytz.utc).replace(hour=time.hour, minute=time.minute).astimezone(tz).strftime("%I:%M %p"))
Which will build what I believe you are looking for:
['04:00 AM', '07:00 PM']
Upvotes: 6