Python中的日期/时间加法/减法

时间:2014-11-25 13:27:47

标签: python-3.x

我的代码现在是:

from datetime import datetime, timedelta
date_format = "%d/%m/%Y %H%M%S"
a = datetime.strptime('19/11/2014 090000', date_format)
b = datetime.strptime('25/11/2014 114736', date_format)
delta = b - a
del_sec = delta.seconds
minutes = del_sec//60
hours = minutes//60
print (delta.days,"day(s) " "%02d:%02d:%02d" " HH:MM:SS"% (hours, minutes % 60, del_sec % 60 ))

哪个也可以包括天;我想要一个变量'c'来存储当前时间,并从现有格式的'c'中减去'a'。

我尝试了不同的组合,但它们无法正常工作。

2 个答案:

答案 0 :(得分:0)

使用strptime创建日期时,它没有时区信息。如果您使用datetime.utcnow()获取当前UTC时间或使用datetime.now()获取计算机时区的当前日期时间,则也是如此。

不确定您在寻找什么。可能不是这个,但也许你可以说为什么它不是你想要的:

b = datetime.strptime('25/11/2014 054736', date_format)
c = datetime.now()
print(b)
print(c)
print(c - b)
  

2014-11-25 05:47:36
   2014-11-25 06:08:41.797725

     

0:21:05.797725

答案 1 :(得分:0)

这应该足以满足大多数日期/时间要求:

//Code tested on Python 3.4 Windows 10 and Android libpython2.6 Android

//Include the following two lines if you want to run the code on Android
//import android
//droid = android.Android()

from datetime import datetime

date_format = "%d/%m/%Y %H%M%S"     // Used for a and b

a = datetime.strptime('23/11/2014 093000', date_format)
b = datetime.strptime('24/11/2014 093000', date_format)
c = datetime.now()
d= datetime.strptime('093000', '%H%M%S')        // Only for time comparison if someone need it.
e= datetime.strptime('093000', '%H%M%S')

delta = c - b                       // Difference between time(s); you can play with a,b and c here since they are in same format

gr=d==e                         // Comparison operator on time if needed can use (>, <, >=, <= and == etc.); time only
print(gr)

fr=c>=b                         // Comparison operator on time if needed can use (>, <, >=, <= and == etc.); date and time                  
print(fr)

days = delta.days

del_sec = delta.seconds
fsec = del_sec%60

minutes = del_sec//60
fmin = minutes%60

fhour = minutes//60

print("%02d:Day(s) %02d:Hour(s) %02d:Minute(s) %02d:Second(s)" %(days,fhour,fmin,fsec))