python - 比较 %H:%M:%S %b %d %Y 中 python 时间的最佳方法
问题描述
我有一个%H:%M:%S %b %d %Y
格式的字符串时间。我可以将当前时间与给定时间进行比较并以分钟为单位的最佳方法是什么?我正在考虑解析字符串中的每个部分并与当前时间的解析字符串进行比较。一定有比这更好的方法
解决方案
You're right, there's certainly an easier way. You may want to try this approach:
- Convert the given string into a
datetime
object. Click here for info on Python's datetime module. See also this answer. - Generate the current time as another
datetime
object. - Get the time difference between the two. This is just a matter of subtracting one from the other. See this answer for an example.
- Convert this to minutes. This is a little trickier. If your two times are
a
andb
, thenc = a-b
gives you a new datetime object representing the difference. You can take the valuesc.days
,c.seconds
andc.microseconds
, then mathematically convert each of the values to minutes, and add them all up.
推荐阅读
- laravel - Cloudflare HTTP 502 每 X 次点击
- queue - 如果给定以下一组命令,队列的内容是什么?
- android - 在 Android Studio 中连接到 Firebase 的 Gradle 的当前版本是什么?
- javascript - 在 javascript/react 中读取表单数据
- javascript - 将变量传递给 html 嵌入式 URL
- javascript - 比较两组对象并使用 javascript 创建新组并形成 jsx
- flutter - Parse Server 获取1km内的所有用户
- firebase - 使用 CLI 加载实时数据库项目
- python - 使用 Keras 预训练模型的 Spark Streaming
- php - 在 php 中,如何在我的代码中修复数组到字符串的转换错误(特别是这一行 - echo " - $msg
" ;?