【问题标题】:why is datetime.strptime not working unable to format?为什么 datetime.strptime 不工作无法格式化?
【发布时间】:2023-02-06 17:26:06
【问题描述】:

我正在从 sqlite 数据库读取进入时间来计算汽车停留的持续时间。 日期时间当前能够插入和检索,但是当格式化为进行计算时,它在使用 datetime.strptime 函数时会一直出错。EnterTime 作为文本存储在 sqlite 数据库中。

import sqlite3
import smtplib
from datetime import datetime, timedelta

# Connect to the database
conn = sqlite3.connect("py.db")

# Get current time
current_time = datetime.now()

# Define the carplate number
carplate = "SJJ4649G"

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

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

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

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

    # Email details
    email = "testcsad69@gmail.com"
    password = "ufwdiqcfepqlepsn"
    send_to = email_result[0][0]
    subject = "Parking Fees"
    message = f"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}."

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

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

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

我已经打印了入口超时,它与数据库中显示的数据相匹配。 我还尝试删除不允许我进行计算的设置。 这是我得到的错误

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

【问题讨论】:

    标签: python sqlite raspberry-pi


    【解决方案1】:

    您需要附加 .%f 以花费微秒:

    from datetime import datetime
    
    entrance_time_str = str(datetime.today())  #                     HERE --v
    entrance_time = datetime.strptime(entrance_time_str, "%Y-%m-%d %H:%M:%S.%f")
    
    >>> entrance_time_str
    '2023-02-06 10:08:15.275026'
    
    >>> entrance_time
    datetime.datetime(2023, 2, 6, 10, 8, 15, 275026)
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多