我怎么能说明两个<代码>日代码>物体之间的时间差异?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
Subtracting the later time from the first time difference = later_time - first_time
creates a datetime object that only holds the difference.
In the example above it is 0 minutes, 8 seconds and 562000 microseconds.
www.un.org/Depts/DGACM/index_spanish.htm 采用日期实例
>>> from datetime import datetime
>>> then = datetime(2012, 3, 5, 23, 8, 15) # Random date in the past
>>> now = datetime.now() # Now
>>> duration = now - then # For build-in functions
>>> duration_in_s = duration.total_seconds() # Total number of seconds between dates
<Duration in years
>>> years = divmod(duration_in_s, 31536000)[0] # Seconds in a year=365*24*60*60 = 31536000.
<>日<>
>>> days = duration.days # Build-in datetime function
>>> days = divmod(duration_in_s, 86400)[0] # Seconds in a day = 86400
<>0> 小时长度:>
>>> hours = divmod(duration_in_s, 3600)[0] # Seconds in an hour = 3600
<<>Durent>
>>> minutes = divmod(duration_in_s, 60)[0] # Seconds in a minute = 60
<>二版>
>>> seconds = duration.seconds # Build-in datetime function
>>> seconds = duration_in_s
缩略语
>>> microseconds = duration.microseconds # Build-in datetime function
www.un.org/Depts/DGACM/index_spanish.htm 两个日期之间的总期限:
>>> days = divmod(duration_in_s, 86400) # Get days (without [0]!)
>>> hours = divmod(days[1], 3600) # Use remainder of days to calc hours
>>> minutes = divmod(hours[1], 60) # Use remainder of hours to calc minutes
>>> seconds = divmod(minutes[1], 1) # Use remainder of minutes to calc seconds
>>> print("Time between dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))
或简单:
>>> print(now - then)
Edit 2019 Since this answer has gained traction, I ll add a function, which might simplify the usage for some
from datetime import datetime
def getDuration(then, now = datetime.now(), interval = "default"):
# Returns a duration as specified by variable interval
# Functions, except totalDuration, returns [quotient, remainder]
duration = now - then # For build-in functions
duration_in_s = duration.total_seconds()
def years():
return divmod(duration_in_s, 31536000) # Seconds in a year=31536000.
def days(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 86400) # Seconds in a day = 86400
def hours(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 3600) # Seconds in an hour = 3600
def minutes(seconds = None):
return divmod(seconds if seconds != None else duration_in_s, 60) # Seconds in a minute = 60
def seconds(seconds = None):
if seconds != None:
return divmod(seconds, 1)
return duration_in_s
def totalDuration():
y = years()
d = days(y[1]) # Use remainder to calculate next variable
h = hours(d[1])
m = minutes(h[1])
s = seconds(m[1])
return "Time between dates: {} years, {} days, {} hours, {} minutes and {} seconds".format(int(y[0]), int(d[0]), int(h[0]), int(m[0]), int(s[0]))
return {
years : int(years()[0]),
days : int(days()[0]),
hours : int(hours()[0]),
minutes : int(minutes()[0]),
seconds : int(seconds()),
default : totalDuration()
}[interval]
# Example usage
then = datetime(2012, 3, 5, 23, 8, 15)
now = datetime.now()
print(getDuration(then)) # E.g. Time between dates: 7 years, 208 days, 21 hours, 19 minutes and 15 seconds
print(getDuration(then, now, years )) # Prints duration in years
print(getDuration(then, now, days )) # days
print(getDuration(then, now, hours )) # hours
print(getDuration(then, now, minutes )) # minutes
print(getDuration(then, now, seconds )) # seconds
Warning: Caveat about built-in .seconds and .microseconds
datetime.seconds
and datetime.microseconds
are capped to [0,86400) and [0,10^6) respectively.
如果时间选择大于最大回报值,就应当谨慎使用。
实例:
>>> start = datetime(2020,12,31,22,0,0,500)
>>> end = datetime(2020,12,31,23,0,0,700)
>>> delta = end - start
>>> delta.microseconds
RESULT: 200
EXPECTED: 3600000200
>>> start = datetime(2020,12,30,22,0,0)
>>> end = datetime(2020,12,31,23,0,0)
>>> delta = end - start
>>> delta.seconds
RESULT: 3600
EXPECTED: 90000
新的第2.7条是<条码> 准时条码> 例法>。 这相当于<条码>(td.microseconds + td.days* 24* 3600) * 10**6 / 10**6。
参考:http://docs.python.org/2/library/datetime.html#datetime.timedelta. Total_seconds
>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds
仅从另一边推倒。 页: 1
>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)
>>> dd = d2 - d1
>>> print (dd.days) # get days
>>> print (dd.seconds) # get seconds
>>> print (dd.microseconds) # get microseconds
>>> print (int(round(dd.total_seconds()/60, 0))) # get minutes
如果a
,b
为时标,则在3/403中找到时间间隔:
from datetime import timedelta
time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)
此前的Adhury版本:
time_difference_in_minutes = time_difference.total_seconds() / 60
如果a
,b
为日元件,例如通过<代码>datetime.now(<>/code>退回,则如果这些物体代表当地时间,且其大小为不同的自动交换机,例如,围绕ST转换或过去/未来日期,则结果可能是错误的。 更详细情况: 如果从日期到<<>之间已过24小时,则Find。
获取可靠的结果,使用超时区或时区实时物体。
使用四舍五入
now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past
d = divmod(now-then,86400) # days
h = divmod(d[1],3600) # hours
m = divmod(h[1],60) # minutes
s = m[1] # seconds
print %d days, %d hours, %d minutes, %d seconds % (d[0],h[0],m[0],s)
仅仅寻找天数:时间选择有一天。 你可以简单地质疑这一点。
>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13
这是我从两个日期到两个日期之间的时间。 日志:
before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
仅仅认为提及形式以及在时间选择方面可能是有益的。 体积是指按格式计算的一定时间。
from datetime import datetime
datetimeFormat = %Y/%m/%d %H:%M:%S.%f
time1 = 2016/03/16 10:01:28.585
time2 = 2016/03/16 09:56:28.067
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)
This will output: 0:05:00.518000
查阅<条码>小时代码>、<条码>分钟代码>和<条码>二代码>。
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m, s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60, m%60, s))
我这样说:
from datetime import datetime
def check_time_difference(t1: datetime, t2: datetime):
t1_date = datetime(
t1.year,
t1.month,
t1.day,
t1.hour,
t1.minute,
t1.second)
t2_date = datetime(
t2.year,
t2.month,
t2.day,
t2.hour,
t2.minute,
t2.second)
t_elapsed = t1_date - t2_date
return t_elapsed
# usage
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)
print(elapsed_time)
#return : 0:08:52
这将使二者出现差异(当时只有60分钟的隔 the):
import time
import datetime
t_start = datetime.datetime.now()
time.sleep(10)
t_end = datetime.datetime.now()
elapsedTime = (t_end - t_start )
print(elapsedTime.total_seconds())
产出:
10.009222
我认为,这是最简单的方式,你不需要担心精确性或过量。
例如,使用<代码>过期失效时间.seconds,你失去许多精确度(重新计算)。 此外,elapsedtime.microseconds
封顶在10^6上,,该回答。 因此,例如,关于第二个<代码>sleep(>,elapsedtime.microseconds
,8325<>> (wrong,应改为
10,000,000
。)
这是在目前时间与930天之间找到区别。
t=datetime.now()-datetime.now().replace(hour=9,minute=30)
seconds_mapping = {
y : 31536000,
m : 2628002.88, # this is approximate, 365 / 12; use with caution
w : 604800,
d : 86400,
h : 3600,
min : 60,
s : 1,
mil : 0.001,
}
def get_duration(d1, d2, interval, with_reminder=False):
if with_reminder:
return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
else:
return (d2 - d1).total_seconds() / seconds_mapping[interval]
我已作过改动,以避免宣布重复性功能,删除了高档的打印缺漏,并增加了对流体、周和ISO个月的支持(根据每个月等于<代码>365/12<>>>/代码的假设,在思想周内只是大致的)。
生产:
d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)
print(get_duration(d1, d2, y , True)) # => (0.0, 2678400.0015)
print(get_duration(d1, d2, m , True)) # => (1.0, 50397.12149999989)
print(get_duration(d1, d2, w , True)) # => (4.0, 259200.00149999978)
print(get_duration(d1, d2, d , True)) # => (31.0, 0.0014999997802078724)
print(get_duration(d1, d2, h , True)) # => (744.0, 0.0014999997802078724)
print(get_duration(d1, d2, min , True)) # => (44640.0, 0.0014999997802078724)
print(get_duration(d1, d2, s , True)) # => (2678400.0, 0.0014999997802078724)
print(get_duration(d1, d2, mil , True)) # => (2678400001.0, 0.0004999997244524721)
print(get_duration(d1, d2, y , False)) # => 0.08493150689687975
print(get_duration(d1, d2, m , False)) # => 1.019176965856293
print(get_duration(d1, d2, w , False)) # => 4.428571431051587
print(get_duration(d1, d2, d , False)) # => 31.00000001736111
print(get_duration(d1, d2, h , False)) # => 744.0000004166666
print(get_duration(d1, d2, min , False)) # => 44640.000024999994
print(get_duration(d1, d2, s , False)) # => 2678400.0015
print(get_duration(d1, d2, mil , False)) # => 2678400001.4999995
以其他方式实现日期之间的区别;
import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)
因此,将在Min获得产出。
增 编
我利用时间差异不断进行融合测试,检查和改进我的职能。 如果有人需要的话,这里简单易行。
from datetime import datetime
class TimeLogger:
time_cursor = None
def pin_time(self):
global time_cursor
time_cursor = datetime.now()
def log(self, text=None) -> float:
global time_cursor
if not time_cursor:
time_cursor = datetime.now()
now = datetime.now()
t_delta = now - time_cursor
seconds = t_delta.total_seconds()
result = str(now) + tl -----------> %.5f % seconds
if text:
result += " " + text
print(result)
self.pin_time()
return seconds
time_logger = TimeLogger()
使用:
from .tests_time_logger import time_logger
class Tests(TestCase):
def test_workflow(self):
time_logger.pin_time()
... my functions here ...
time_logger.log()
... other function(s) ...
time_logger.log(text= Tests finished )
(一) 具有与原木产出相似之处
2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234 Tests finished
您可能认为,这一快速征兆在不长的间隔时间内是有用的:
from datetime import datetime as dttm
time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
delta = dttm.now() - time_ago
days = delta.days # can be converted into years which complicates a bit…
hours, minutes, seconds = map(int, delta.__format__( ).split( . )[0].split( )[-1].split( : ))
页: 1
这里的答案很容易概括或变成一种功能,是合理的契约,易于遵循。
ts_start=datetime(2020, 12, 1, 3, 9, 45)
ts_end=datetime.now()
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
days,secs=divmod(secs,secs_per_day:=60*60*24)
hrs,secs=divmod(secs,secs_per_hr:=60*60)
mins,secs=divmod(secs,secs_per_min:=60)
secs=round(secs, 2)
answer= Duration={} days, {} hrs, {} mins and {} secs .format(int(days),int(hrs),int(mins),secs)
print(answer)
它以<代码>Duration=270天、10小时、32分钟和42.13 secs的形式作了答复。
这可能帮助某人,发现这种方法已经过期,或者没有用这种方法计算时间。 代码
dt.microseconds
也可提供
from datetime import datetime
# updated_at = "2022-10-20T07:18:56.950563"
def is_expired(updated_at):
expires_in = 7 #days
datetime_format = %Y-%m-%dT%H:%M:%S.%f
time_difference = datetime.now() - datetime.strptime(updated_at, datetime_format)
return True if time_difference.days > expires_in else False
import datetime
date = datetime.date(1, 1, 1)
#combine a dummy date to the time
datetime1 = datetime.datetime.combine(date, start_time)
datetime2 = datetime.datetime.combine(date, stop_time)
#compute the difference
time_elapsed = datetime1 - datetime2
start_time --> start time for datetime object
end_time--> end time for datetime object
we cannot directly subtract the datetime.time objects
hence we need to add a random date to it (we use combine)
or you can use the "today" instead of (1,1,1)
希望这一帮助
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding