python - 所以我有这个正在使用的文本文件,我想将其中的信息用于我的停车系统
问题描述
我的文本文件中的一行:
RCF585 medium Joseph -you entered the parking lot at 3:30 and left at 4:30-
我想要做的是通过车牌号识别汽车,然后知道它是“中型”(它的大小),因此它的总成本是(停车费 * 1.25(税))同时总small is (停车费 * 1.00) 和 big (停车费 * 1.50)。
停车费(每半小时 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 - 在 Python 上使用 Selenium 返回的空“src”属性
- java - 如何让 Retrofit 取消转义 HTML 转义符号?
- docker - 创建覆盖挂载到 /var/lib/docker/overlay2/ 时出错
- css - Django & css : 在 django 表单字段上应用 Css
- scala - 解压缩多个 *.gz 文件并在 spark scala 中制作一个 csv 文件
- javascript - 具有多个条件的 JavaScript if 语句并检查输入是否为空
- json - 仅当 AWS Cloudformation 不存在时,如何通过它创建 AWS ECS 集群
- django-models - 如何在不传递外键值的情况下过滤 django 形式的外键?
- python - K-fold CV 的变体,其中 size(test_set) > N/K
- python - 从python将带有微秒的日期时间插入SQL Server