Accounting for AM PM in strptime not working - python

I am following another search thread here, but it is not working. Anytime I include %p to get AM/PM, I get the following error:
ValueError: time data '11:30' does not match format '%I:%M%p'
This is true if I have '%I:%M %p' or '%I:%M%p'. If I leave the %p off it works fine, but that defeats the purpose of getting AM PM
# my code
from datetime import datetime
date_string = '11:30'
format = '%I:%M %p'
my_date = datetime.strptime(date_string, format)
my_date.strftime(format)

You just need to provide same format of your time in strptime function. And then use AM/PM format ('%I:%M %p') in strftime function.
from datetime import datetime
def getTime(time_string):
time_object = datetime.strptime(time_string,'%H:%M') #Covert string to time object
return time_object.strftime('%I:%M %p') #Convert time object to AM/PM format
getTime('11:30')
Output: 11:30 am
getTime('13:30')
Output: 01:30 pm

Yes, cause you need to add if it's AM or PM to match the format.
from datetime import datetime
date_string = '11:30 AM'
format = '%I:%M %p'
my_date = datetime.strptime(date_string, format)
my_date.strftime(format)
%I matches hour, %M matches minutes, %p matches AM/PM

The format strings provided strptime (...) must match exactly.
If you do not know which format your time is in, you can try multiple ones:
from datetime import datetime
def getTime(text, formats = ['%I:%M %p','%I:%M']):
"""Tries different patterns to create a time from text.
First format with match wins.
As default the time is parsed with am/pm, as fallback without it."""
for pattern in formats:
try:
return datetime.strptime(text, pattern)
except:
pass # catch all errors
# nothing matched, return None
raise ValueError("No format {} matched '{}'".format(formats,text))
a_time = getTime("11:42") # produces an am time
b_time = getTime("11:42 pm") # produces a pm time
print(a_time.strftime("%I:%M %p"))
print(b_time.strftime("%I:%M %p"))
try:
c_time = getTime("does not work")
except ValueError as e:
print(type(e),e)
Output:
11:42 AM
11:42 PM
<class 'ValueError'> No format ['%I:%M %p', '%I:%M'] matched 'does not work'

Related

How to format string time object with python?

I am using django python. Now I want to convert the following timing string into hours, minutes ,am/pm format.
string_time = '2022-09-13 11:00:00.996795+00'
expected output:
11:00 am
actual output is :
ValueError: time data '2022-09-13 11:00:00.996795+00' does not match format '%m/%d/%y %H:%M:%S'
my code :
def time_slots(self,string_time='2022-09-13 11:00:00.996795+00'):
print(datetime.strptime(string_time, '%m/%d/%y %H:%M:%S'),type(start_time))
start_time = datetime.strptime(string_time, '%m/%d/%y %H:%M:%S')
return formated_start_time
When you remove the last three chars ('+00') and replace the space with T you can use datetime.datetime.fromisoformat(str) to get a datetime object.
from datetime import datetime
timestr = '2022-09-13 11:00:00.996795+00'
timestr = timestr.rstrip(timestr[-3:]).replace(' ', 'T')
date = datetime.fromisoformat(timestr)
from there you can use date.hour and date.minute to get the values you want.
e.g.:
hour = date.hour%12
minute = date.minute
addition = ''
if date.hour > 12:
addition = 'pm'
else:
addition = 'am'
print(f'{hour}:{minute} {addition}')
I'm not sure if the last string +00 is useful.
If not, the following implementation can help you.
from datetime import datetime
def time_slots(string_time='2022-09-13 11:00:00.996795+00'):
date = datetime.strptime(string_time[:-3], '%Y-%m-%d %H:%M:%S.%f')
return date.strftime("%H:%M %p")
output = time_slots()
print(output) # the output is: 11:00 AM
You can use the parse function provided by dateutil:
from dateutil import parse
string_time = '2022-09-13 11:00:00.996795+00'
dt = parse(string_time)
return dt.strftime("%H:%M %p")
Result: 11:00 AM

Python strptime not parsing time zone EST %z

I am trying to parse the string '10/23/2019 6:02:05 PM EST' into a datetime with time zone using Python 3.7.
Code:
from datetime import datetime
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p %Z')
Error:
ValueError: time data '10/23/2019 6:02:05 PM EST' does not match format '%m/%d/%Y %I:%M:%S %p %Z'
When I create a datetime and output it using the same formatting I get the correct output. The only difference is that there is a 0 in front of the hour, but adding 0 in front of the 6 in my date string results in the same error.
My current solution is to parse the datetime without the timezone and then localize it, but this is not ideal.
date_lst = date.split()
date_str = ' '.join(date_lst[0:3])
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
new_tz = pytz.timezone(date_lst[3])
timestamp_tz = new_tz.localize(timestamp)```
It is reasonable to expect that parsing a string with a timezone included would produce a timezone aware datetime object.
Try it
>>timestamp = datetime.strptime('10/23/2019 6:02:05 PM EST', '%m/%d/%Y %I:%M:%S %p EST')
>>2019-10-23 06:02:05
You can try this.

How do i check if timezone is present in a unicode string using Python

I am having timestamp fields in my JSON data where some of the timestamps have timestamp in this format str("2014-05-12 00:00:00") and another in this format str("2015-01-20 08:28:16 UTC"). I would like to get year, month, day fields only from the string. I have tried the following approach but not sure what is the problem. Can someone please correct me. I have searched some of the answers from StackOverflow but nothing helped me.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
def convert_timestamp(date_timestamp=None):
if '%Z' in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
I've tried following code to search timezone in str and its working.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
zone=date_posted_zone.split(" ")
print(zone[2])
def convert_timestamp(date_timestamp=None):
if zone[2] in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
You're checking if the literal string %Z is in the timestamp value; only strptime (and strftime) can actually make use of the format character.
What you can do is simply try to parse the string as if it had a timezone, and if that fails, try to parse it without.
def convert_timestamp(date_timestamp=None):
try:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
except ValueError:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
Of course, as written, you don't really need to parse the string at all; just split it on whitespace and return the first component. (Your existing code already assumes that the year/month/date matches.)
def convert_timestamp(date_timestamp):
return date_timestamp.split()[0]
from dateutil import parser
datetime_no_timezone = parser.parse("2015-01-20 08:28:16")
datetime_with_timezone = parser.parse("2015-01-20 08:28:16+02:00")
if datetime_no_timezone.tz == None:
# CODE ALWAYS GO THROUGH THIS
pass
if datetime_no_timezone.tz:
# CODE ALWAYS GO THROUGH THIS
pass

Create a datetime from a string representation in a CSV file

I have a CSV file with recorded datetimes with a particular format:
%Y-%m-%d %H:%M:%s %Z
Example:
2017-02-11 14:11:42 PST
I am trying to format the datetime to a friendlier value to use later on.
However, I have been unable to create a datetime object with my code so far.
Here is my code:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y/%m/%d %H:%M:%S %Z")
)
This is the error received:
ValueError: time data '2017-02-11 14:11:42 PST' does not match format %Y/%m/%d %H:%M:%S %Z'
Timezones are often rather wonky when trying to convert from a string. It is often best to deal with the timezone string yourself. Here is a bit of code which separates the timezone from the timestamp, and then converts them separately.
Code:
import datetime as dt
import pytz
my_timezones = dict(
PST='US/Pacific',
)
def convert_my_datetime_str(dt_str):
# split into time and timezone
timestamp, tz_str = dt_str.rsplit(' ', 1)
# convert the date string to datetime
time = dt.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
# get a timezone name
tz = pytz.timezone(my_timezones[tz_str])
# return a timezone aware datetime
return tz.localize(time)
Test Code:
print(convert_my_datetime_str('2017-02-11 14:11:42 PST'))
Results;
2017-02-11 14:11:42-08:00
You should be able to just change the format to match your date strings. In the error, your date string has dashes instead of slashes, so make the format string match:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y-%m-%d %H:%M:%S %Z")
)

Convert String to Python datetime Object without Zero Padding

I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM

Categories

Resources