Time value does not match the format. ValueError in python - python

I am trying to convert a string to datetime object using the strptime function.
I am encountering a ValueError that says format doesn't match, so I did double checking and confirmed that the format in the string matches the format I am passing as the parameter for strptime.
I have also referenced this question: time data does not match format but there the month and year were swapped.
So does this only work with the '%y-%m-%d %H:%M:%S' format or is it dynamic as per the user input like in my case '%y-%m-%d-%H:%M:%S' ?
input:-
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%y-%m-%d-%H:%M:%S')
output
ValueError: time data '2022-09-31-01:17:46' does not match format '%y-%m-%d-%H:%M:%S'
Expected output:
#while printing 'do'
2020-09-31-01:17:46

You're almost there. You need %Y instead of %y since you're providing the year with the century (2022 instead of 22).
Your code would be
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%Y-%m-%d-%H:%M:%S')

Related

How to keep leading zeros in datetime to string conversion?

I am facing an issue whenever I try to convert a datetime object into string that has leading zeros in the year
Suppose d is my datetime object:
d = '0021-01-12 03:12:28'
d_str = d.strftime("%Y-%m-%d %H:%M:%S.%f")
The output of printing d_str is always (regardless of %Y or %y)
'21-01-12 03:12:28.000000'
The desired output should have leading zeros for the year
'0021-01-12 03:12:28.000000'
The datetime documentation suggests one of %y or %Y format codes should work, however, I have tried both options and they do not work.
Is there a way to do this using the datetime library or do I need to write custom logic?
Try this (edited to reflect suggestion in comment)
d.strftime("%y-%m-%d %H:%M:%S.%f").zfill(26)

string convert to date time in python

I have a list of date time strings like this.
16-Aug-2019
I want to convert the string to 2019-08-01 this date format, and I have tried on this code , but it's getting me an error.
formatd_date = datetime.strptime(formatd_date, '%y-%m-%d')
ValueError: time data 'As-of' does not match format '%y-%m-%d'
If any can help, it will be huge thank.
Convert to datetime format and then convert to string format you want to:
>>> from datetime import datetime
>>> a = "16-Aug-2019"
>>> datetime.strptime(a, "%d-%b-%Y").strftime("%Y-%m-%d")
'2019-08-16'
Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Just fails because %y is 2-digit year. Use %Y for 4-digit year.

How to match the format “Sep-14” for converting it to DATETIME

I am trying to transform the column, 'issue_d' by year.
below is the code I have used but it gives me error
dt_series = pd.to_datetime(df['issue_d'], format= '%m-%Y')
df['year'] = dt_series.dt.year
this is the error message
ValueError: time data 'Sep-14' does not match format '%m-%Y' (match)
Looking at the error, I am pretty sure that df['issue_d] = 'Sep-14'. That means that you are using the wrong format string. The format string you have specified expects the months as digits and the full year (4 digits), i.e., '09-2014'
What you want as a format string is '%b-%y' which takes the abbriviated month name in your locale and the year as two digits (starting at 2000). Thus, your line should look like
dt_series = pd.to_datetime(df['issue_d'], format= '%b-%y')
The different formats can be found in the Python datetime documentation, found here.

Converting string to datetime with milliseconds and timezone - Python

I have the following python snippet:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object
However when I execute the code, I'm getting the following error:
ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'
what's wrong with my matching expression?
EDIT 2: According to this post, strptime doesn't support %z (despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)
Gives the following output:
$ python date.py
2015-01-05 17:47:59
EDIT: Your datetime.strptime argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'
With strptime(), %y refers to
Year without century as a zero-padded decimal number
I.e. 01, 99, etc.
If you want to use the full 4-digit year, you need to use %Y
Similarly, if you want to use the 3-letter month, you need to use %b, not %m
I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
And UTC offset is lowercase z.

Python unit-testing: Check if datestring is in the allowed format

I'm unittesting my code and I want to make sure that the timestamps I get in are:
strings
In the format YYYY<space>DDD:HH:MM:SS.sss<space> where DDD represents the day of the year.
What I've got is:
def test_time(self, time_stamp)
from datetime import datetime
self.assertIsInstance(time_stamp,str, msg="%s not a string" %time_stamp)
self.assertIsInstance(datetime.strptime(time_stamp, "%Y %j:%H:%M:%S.%f"), datetime.datetime)
The problem with this is that it the second assert is true for both 2014 031:09:59:59.862 (correct timestamp) and 2014 31:9:59:59.862 (incorrect timestamp).
How can I check that the timestamp has the correct format?
You can follow strptime by strftime to normalize the string to your desired format, and check if the original string equals the normalized string.

Categories

Resources