首页 > 解决方案 > 比较 %H:%M:%S %b %d %Y 中 python 时间的最佳方法

问题描述

我有一个%H:%M:%S %b %d %Y格式的字符串时间。我可以将当​​前时间与给定时间进行比较并以分钟为单位的最佳方法是什么?我正在考虑解析字符串中的每个部分并与当前时间的解析字符串进行比较。一定有比这更好的方法

标签: python

解决方案


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 and b, then c = a-b gives you a new datetime object representing the difference. You can take the values c.days, c.seconds and c.microseconds, then mathematically convert each of the values to minutes, and add them all up.

推荐阅读