datetime.strptime无法格式化的原因是什么?

huangapple go评论75阅读模式
英文:

why is datetime.strptime not working unable to format?

问题

我从SQLite数据库中读取入口时间,以计算汽车停留的持续时间。日期时间目前可以插入和检索,但在格式化以进行计算时,使用datetime.strptime函数时会出现错误。EnterTime以文本形式存储在SQLite数据库中。

我已经打印出入口时间,并与数据库中显示的数据相匹配。我还尝试删除会阻止我进行计算的格式。以下是我收到的错误消息:

2023-02-06 16:07:46.640395
Traceback (most recent call last):
  File "/media/pi/6134-E775/payment.py", line 32, in <module>
    entrance_time = datetime.strptime(entrance_time_str, "%Y-%m-%d %H:%M:%S")
  File "/usr/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/lib/python3.7/_strptime.py", line 362, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .640395

这个错误是因为datetime.strptime无法解析毫秒部分(.640395)。您可以通过修改日期时间格式字符串来解决此问题。如果您不需要毫秒部分,可以将格式字符串更改为"%Y-%m-%d %H:%M:%S",并丢弃毫秒数据。如下所示:

entrance_time = datetime.strptime(entrance_time_str, "%Y-%m-%d %H:%M:%S")

这将从entrance_time_str中解析日期时间,忽略毫秒部分,并继续进行计算。希望这对您有所帮助。

英文:

i am reading a entrance time from sqlite database to calaulate the duration of the car stay.
the datetime is currenly able to insert and retrive but when formated to do calualtion it keeps give an error when using the datetime.strptime funtion.EnterTime is stored as a text in the sqlite database.

import sqlite3
import smtplib
from datetime import datetime, timedelta

# Connect to the database
conn = sqlite3.connect(&quot;py.db&quot;)

# Get current time
current_time = datetime.now()

# Define the carplate number
carplate = &quot;SJJ4649G&quot;

# Check if the carplate already exists in the database
cursor = conn.cursor()
query = &quot;SELECT * FROM entrance WHERE carplate = ?&quot;
cursor.execute(query, (carplate,))
result = cursor.fetchall()

# If the carplate already exists, send an email
if len(result) &gt; 0:
    # Get the email address from the gov_info table
    query = &quot;SELECT email FROM gov_info WHERE carplate = ?&quot;
    cursor.execute(query, (carplate,))
    email_result = cursor.fetchall()

    # Get the entrance time from the entrance table
    query = &quot;SELECT EnterTime FROM entrance WHERE carplate = ?&quot;
    cursor.execute(query, (carplate,))
    entrance_time_str = cursor.fetchone()[0]
    print (entrance_time_str)
    entrance_time = datetime.strptime(entrance_time_str, &quot;%Y-%m-%d %H:%M:%S&quot;)

    # Calculate the cost
    delta = current_time - entrance_time
    cost = delta.total_seconds() / 3600 * 10  # 10 is the hourly rate

    # Email details
    email = &quot;testcsad69@gmail.com&quot;
    password = &quot;ufwdiqcfepqlepsn&quot;
    send_to = email_result[0][0]
    subject = &quot;Parking Fees&quot;
    message = f&quot;The cost for parking the car with plate number {carplate} is ${cost:.2f}. The entrance time was {entrance_time} and the current time is {current_time}.&quot;

    # Send the email
    smtp = smtplib.SMTP(&#39;smtp.gmail.com&#39;, 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.login(email, password)
    smtp.sendmail(email, send_to, f&quot;Subject: {subject}\n\n{message}&quot;)
    smtp.quit()

# If the carplate does not exist, insert it into the database
else:
    query = &quot;INSERT INTO entrance (carplate, EnterTime) VALUES (?, ?)&quot;
    cursor.execute(query, (carplate, current_time))
    conn.commit()

# Close the connection
cursor.close()
conn.close()

i have printed the entrance time out and it matches the data shown in the database.
i have also tried to remove the fromating that would not let me do the calulations.
this is the error i get

2023-02-06 16:07:46.640395
Traceback (most recent call last):
  File &quot;/media/pi/6134-E775/payment.py&quot;, line 32, in &lt;module&gt;
    entrance_time = datetime.strptime(entrance_time_str, &quot;%Y-%m-%d %H:%M:%S&quot;)
  File &quot;/usr/lib/python3.7/_strptime.py&quot;, line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File &quot;/usr/lib/python3.7/_strptime.py&quot;, line 362, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: .640395

答案1

得分: 0

你需要在后面添加 .%f 以获取微秒部分:

entrance_time_str = '2023-02-06 16:07:46.640395'  #              HERE --v
entrance_time = datetime.strptime(entrance_time_str, "%Y-%m-%d %H:%M:%S.%f")
>>> entrance_time_str
'2023-02-06 16:07:46.640395'

>>> entrance_time
datetime.datetime(2023, 2, 6, 16, 7, 46, 640395)
英文:

You need to append .%f to take microseconds:

entrance_time_str = &#39;2023-02-06 16:07:46.640395&#39;  #              HERE --v
entrance_time = datetime.strptime(entrance_time_str, &quot;%Y-%m-%d %H:%M:%S.%f&quot;)
&gt;&gt;&gt; entrance_time_str
&#39;2023-02-06 16:07:46.640395&#39;

&gt;&gt;&gt; entrance_time
datetime.datetime(2023, 2, 6, 16, 7, 46, 640395)

huangapple
  • 本文由 发表于 2023年2月6日 16:57:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359164.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定