The following lines
new_variable = dataset['Time'].units[14:].rstrip()
print ("NEW VARIABLE ", new_variable, type(new_variable), len(new_variable))
datetime_variable = datetime.datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')
produces the following output
NEW VARIABLE 2025-02-07 00:00:00 <class 'str'> 19
but generates the following error
datetime_variable = datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')
File "/usr/lib/python3.10/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/lib/python3.10/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2025-02-07 00:00:00' does not match format '%y-%m-%d %H:%M:%S'
I really don't understand why datetime complains about the string format or how to fix it.
The following lines
new_variable = dataset['Time'].units[14:].rstrip()
print ("NEW VARIABLE ", new_variable, type(new_variable), len(new_variable))
datetime_variable = datetime.datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')
produces the following output
NEW VARIABLE 2025-02-07 00:00:00 <class 'str'> 19
but generates the following error
datetime_variable = datetime.strptime(new_variable, '%y-%m-%d %H:%M:%S')
File "/usr/lib/python3.10/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/lib/python3.10/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2025-02-07 00:00:00' does not match format '%y-%m-%d %H:%M:%S'
I really don't understand why datetime complains about the string format or how to fix it.
Share Improve this question edited Feb 16 at 14:52 Mark Tolonen 178k26 gold badges180 silver badges269 bronze badges asked Feb 15 at 19:57 afernandezodyafernandezody 1318 bronze badges 2- docs.python./3/library/datetime.html#format-codes – jonrsharpe Commented Feb 15 at 20:03
- Thanks! What was I thinking? – afernandezody Commented Feb 15 at 20:42
1 Answer
Reset to default 0The problem with your function is that it the %y
placeholder expects a two-digit year (without the century). You should replace your code with %Y
, which reads a full year (or, of course, modify your input accordingly):
import datetime
datetime_variable = datetime.datetime.strptime("2025-02-16 00:00:00", '%Y-%m-%d %H:%M:%S')
print(datetime_variable)