python - 所以我正在使用这个文本文件,我想将其中的信息用于我的 parking 系统

标签 python

我的文本文件中的一行:

RCF585 medium Joseph -you entered the parking lot at 3:30 and left at 4:30- 

我想要做的是通过车牌号码识别汽车,然后知道它是“中型”(它的大小),因此它的总成本是( parking 费* 1.25(税))小的总和是( parking 费 * 1.00),大的总和是( parking 费 * 1.50)。

parking 费用(每半小时20美元)当然取决于汽车停放的时间,所以我的第二个问题是如何通过读取相关汽车的线路来读取和识别汽车的停放时间。这是我迄今为止成功编写的内容:

f=open(file, "r")

which_car= input("Please write your license number: ")

for line in f:

if line.startswith(which_car):        #identifying which car we want to deal with

最佳答案

您可以使用re.findall()提取时间,和datetime.datetime.strptime()将提取的字符串转换为日期时间数据:

import re
from datetime import datetime

which_car = input("Please write your license number: ")
file = "text.txt"

with open(file, "r") as f:
    for line in f:
        if line.startswith(which_car):
            time1, time2 = re.findall("\d+:\d+", line)

def string_to_time(string):
    return datetime.strptime(string , '%H:%M')

print(string_to_time(time2) - string_to_time(time1))

测试运行:

Please write your license number: RCF585

输出:

1:00:00

说明:

模式\d+:\d+表示仅冒号两侧的数字,格式%H:%M表示小时值和分钟值在冒号的相对两侧。

注意:使用 = 运算符将 open 调用分配给变量是一种不好的做法。相反,请使用 with声明。

关于python - 所以我正在使用这个文本文件,我想将其中的信息用于我的 parking 系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65599624/

相关文章:

python - 在 MySql 中存储一个 Pickle

python - 为什么在我遍历 pandas DataFrame 后这个函数 "take"不起作用?

python - 有条件地导入模块以影子本地实现

python - 如何在Python中获取多个字符输入并对其进行处理

python 2.7 : can I make Matplotlib display values like Plotly?

python - Openerp : new module is not showing into module list

Python 序列和子序列的排列

python - Anaconda Jupyter Notebook 突然无法启动内核

python - 如何获得ipython并行处理的中间结果?

python - 类型错误 : Object of type ResultProxy is not JSON serializable: result in sqlalchemy query?