strptime with timestamp and AM/PM - python

I am trying to convert from string to timestamp using:
from datetime import datetime
date_object = datetime.strptime('09-MAR-15 12.54.45.000000000 AM', '%d-%b-%y %I.%M.%S.%f %p')
I get:
ValueError:
time data '09-MAR-15 12.54.45.000000000 AM' does not match format
'%d-%b-%y %I.%M.%S.%f %p'

The below will work as long as the the part after the decimal point always ends in 000. :-) %f captures microseconds, while I guess your timestamp uses nanoseconds?
date_object = datetime.strptime('09-MAR-15 12.54.45.000000000 AM',
'%d-%b-%y %I.%M.%S.%f000 %p')
You might consider just chopping off those three digits. E.g.
date_object = datetime.strptime(
re.sub(r'\d{3}( .M)$', r'\1', '09-MAR-15 12.54.45.000000000 AM'),
'%d-%b-%y %I.%M.%S.%f %p')

Related

ValueError in time-date data

I'm facing issue in matching the format of time date data
time data '03-MAY-22 02.42.33.000000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p'
what should be the correct format for this date-time data?
For this time-date data '03-MAY-22 02.42.33.000000000 AM'
I've written this format '%d-%b-%y %I.%M.%S.%f %p' but this is not matching
The standard library doesn't support a resolution for the fraction-of-second finer than microseconds. You can remove the last three digits from the fraction-of-second and then parse the obtained string in the usual way.
from datetime import datetime
import re
str_dt = '03-MAY-22 02.42.33.000000000 AM'
str_dt = re.sub(r'(\.\d{6})(\d{3})', r'\1', str_dt)
print(str_dt)
dt = datetime.strptime('03-MAY-22 02.42.33.000000 AM', '%d-%b-%y %H.%M.%S.%f %p')
print(dt)
Output:
03-MAY-22 02.42.33.000000 AM
2022-05-03 02:42:33
Check this regex demo to understand the regex pattern used in the solution. This solution replaces the regex match with group 1 of the match.

Value error while using datetime.datetime.strptime

I want to covert a string item to the datetime format that I require.
The string item is this : '3/27/2013 2:54:00 PM'
My code is as follows: map(datetime.datetime.strptime,'3/27/2013 2:54:00 PM', '%m/%d/%Y %I:%M:%S %p')
I get the following error : stray % in format '%'
Any help is appreciated.
Not sure why you use map, you can just use strptime on that string, worked for me
import datetime
dt = datetime.datetime.strptime('3/27/2013 2:54:00 PM', '%m/%d/%Y %I:%M:%S %p')
print(dt)

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.

Accounting for AM PM in strptime not working

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'

python strptime wrong format with 12-hour hour

My string format currently is datetime.strptime(date_as_string, '%d/%m/%y %I:%M %p')
this unfortunately does not work with input such as 1/12/07 00:07 AM
How I can get strptime to recogize this format ?
EDIT:
ValueError: time data '1/12/07 00:07 AM' does not match format '%d/%m/%y %I:%M %p'
'00' is not a valid 12-hour hour, but if your input date string is inconsistently formatted you might be able to get away with something like this:
>>> from datetime import datetime as dt
>>> date_as_string = '1/12/07 00:07 AM'
>>> format_12 = '%d/%m/%y %I:%M %p'
>>> format_24 = '%d/%m/%y %H:%M %p'
>>> date_string, time_string = date_as_string.split(' ', 1)
>>> try:
... dt.strptime(date_string + ' ' + time_string, format_12)
... except ValueError:
... dt.strptime(date_string + ' ' + time_string, format_24)
...
datetime.datetime(2007, 12, 1, 0, 7)
'1/12/07 00:07 AM' has incorrect format because in the 12-hour format the hour can be in range 1-12 and not 0.

Categories

Resources