You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手遇ValueError:无法将'26.02.2018'转为十进制整数求助

Fixing the ValueError: invalid literal for int() with base 10 in Your Python Date Code

Hey there! Let's break down why you're hitting this error and get your script back on track quickly.

What's Causing the Error?

That error happens because you’re trying to use int() on the string '26.02.2018'—and Python can’t convert a date-formatted string (with dots separating day/month/year) into an integer directly. The int() function only works on strings that are pure whole numbers (like '26' or '2018'), not strings with non-digit separators or mixed date components.

Solutions Based on Your Goal

Depending on what you want to do with that date, here are tailored fixes:

1. Extract Individual Date Parts as Integers

If you just need the day, month, and year as separate integers, split the string first then convert each segment:

date_str = '26.02.2018'
# Split the string by '.' and convert each part to int
day, month, year = map(int, date_str.split('.'))
print(f"Day: {day}, Month: {month}, Year: {year}")
# Output: Day: 26, Month: 2, Year: 2018

2. Convert to a Proper Date Object (Recommended)

If you plan to do date-related operations (like calculating differences, reformatting, etc.), use Python’s built-in datetime module to parse the string into a usable date object:

from datetime import datetime

date_str = '26.02.2018'
# The format string '%d.%m.%Y' matches your DD.MM.YYYY input
date_object = datetime.strptime(date_str, '%d.%m.%Y')
print(f"Parsed date: {date_object}")
# Output: 2018-02-26 00:00:00

# If you need an integer (like a Unix timestamp), convert it like this:
timestamp = int(date_object.timestamp())
print(f"Unix timestamp: {timestamp}")

3. Add Error Handling for Robustness

If your script deals with user input or external data, add a try-except block to catch invalid date formats gracefully:

from datetime import datetime

def safe_parse_date(date_input):
    try:
        return datetime.strptime(date_input, '%d.%m.%Y')
    except ValueError:
        print(f"Oops! '{date_input}' isn't a valid DD.MM.YYYY date. Double-check the format.")
        return None

# Test the function
my_date = safe_parse_date('26.02.2018')
if my_date:
    print(f"Success! Formatted date: {my_date.strftime('%B %d, %Y')}")
# Output: Success! Formatted date: February 26, 2018

内容的提问来源于stack exchange,提问作者RelaxxxedMato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:17:13