最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Datetime keeps complaining about string format - Stack Overflow

programmeradmin4浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

The 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)
发布评论

评论列表(0)

  1. 暂无评论