标签归档:time

在Python中,如何以可读格式显示当前时间

问题:在Python中,如何以可读格式显示当前时间

如何将当前时间显示为:

12:18PM EST on Oct 18, 2010

在Python中 谢谢。

How can I display the current time as:

12:18PM EST on Oct 18, 2010

in Python. Thanks.


回答 0

首先是快速而肮脏的方法,其次是精确的方法(识别日光的节省与否)。

import time
time.ctime() # 'Mon Oct 18 13:35:29 2010'
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010'
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010'

First the quick and dirty way, and second the precise way (recognizing daylight’s savings or not).

import time
time.ctime() # 'Mon Oct 18 13:35:29 2010'
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010'
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010'

回答 1

您所需要的只是文档中

import time
time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'

All you need is in the documentation.

import time
time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'

回答 2

您可以执行以下操作:

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

有关%代码的完整文档位于http://docs.python.org/library/time.html

You could do something like:

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

The full doc on the % codes are at http://docs.python.org/library/time.html


回答 3

import time
time.strftime('%H:%M%p %Z on %b %d, %Y')

这可能会派上用场:http : //strftime.org/

import time
time.strftime('%H:%M%p %Z on %b %d, %Y')

This may come in handy


回答 4

通过使用此代码,您将获得实时时区。

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

By using this code, you’ll get your live time zone.

import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))

回答 5

看一下http://docs.python.org/library/time.html提供的功能

您在那里有几个转换功能。

编辑:请参阅datetime(http://docs.python.org/library/datetime.html#module-datetime),以获得更多类似OOP的解决方案。time上面链接的库有点必要。

Take a look at the facilities provided by the time module

You have several conversion functions there.

Edit: see the datetime module for more OOP-like solutions. The time library linked above is kinda imperative.


如何测量python中代码行之间的时间?

问题:如何测量python中代码行之间的时间?

因此,在Java中,我们可以执行如何测量函数执行所需的时间

但是如何在python中完成呢?要测量代码行之间的时间开始和结束时间?这样做的事情:

import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured() 
endtime = some_time_library.some_module()

time_taken = endtime - starttime

So in Java, we can do How to measure time taken by a function to execute

But how is it done in python? To measure the time start and end time between lines of codes? Something that does this:

import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured() 
endtime = some_time_library.some_module()

time_taken = endtime - starttime

回答 0

如果要测量CPU时间,可以time.process_time()用于Python 3.3及更高版本:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

第一个电话打开计时器,第二个电话告诉您已经过去了几秒钟。

还有一个功能time.clock(),但是自Python 3.3起不推荐使用,并将在Python 3.8中删除。

有更好的性能分析工具,例如timeitprofile,但是time.process_time()将测量CPU时间,这就是您要的内容。

如果您想测量挂钟时间,请使用time.time()

If you want to measure CPU time, can use time.process_time() for Python 3.3 and above:

import time
start = time.process_time()
# your code here    
print(time.process_time() - start)

First call turns the timer on, and second call tells you how many seconds have elapsed.

There is also a function time.clock(), but it is deprecated since Python 3.3 and will be removed in Python 3.8.

There are better profiling tools like timeit and profile, however time.process_time() will measure the CPU time and this is what you’re are asking about.

If you want to measure wall clock time instead, use time.time().


回答 1

您还可以使用time库:

import time

start = time.time()

# your code

# end

print(f'Time: {time.time() - start}')

You can also use time library:

import time

start = time.time()

# your code

# end

print(f'Time: {time.time() - start}')

回答 2

借助小型便利类,您可以像这样测量缩进行中所花费的时间

with CodeTimer():
   line_to_measure()
   another_line()
   # etc...

缩进的行完成执行后,将显示以下内容:

Code block took: x.xxx ms

更新:现在,您可以使用pip install linetimer然后获取类from linetimer import CodeTimer。请参阅此GitHub项目

以上类的代码:

import timeit

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = timeit.default_timer()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (timeit.default_timer() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')

然后,您可以命名要测量的代码块

with CodeTimer('loop 1'):
   for i in range(100000):
      pass

with CodeTimer('loop 2'):
   for i in range(100000):
      pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms

嵌套它们:

with CodeTimer('Outer'):
   for i in range(100000):
      pass

   with CodeTimer('Inner'):
      for i in range(100000):
         pass

   for i in range(100000):
      pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms

关于timeit.default_timer(),它使用基于OS和Python版本的最佳计时器,请参见此答案

With a help of a small convenience class, you can measure time spent in indented lines like this:

with CodeTimer():
   line_to_measure()
   another_line()
   # etc...

Which will show the following after the indented line(s) finishes executing:

Code block took: x.xxx ms

UPDATE: You can now get the class with pip install linetimer and then from linetimer import CodeTimer. See this GitHub project.

The code for above class:

import timeit

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = timeit.default_timer()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (timeit.default_timer() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')

You could then name the code blocks you want to measure:

with CodeTimer('loop 1'):
   for i in range(100000):
      pass

with CodeTimer('loop 2'):
   for i in range(100000):
      pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms

And nest them:

with CodeTimer('Outer'):
   for i in range(100000):
      pass

   with CodeTimer('Inner'):
      for i in range(100000):
         pass

   for i in range(100000):
      pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms

Regarding timeit.default_timer(), it uses the best timer based on OS and Python version, see this answer.


回答 3

我总是喜欢以小时,分钟和秒(%H:%M:%S)格式检查时间:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken) 

输出:

Time:  0:00:00.000019

I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:

from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken) 

output:

Time:  0:00:00.000019

回答 4

我一直在寻找一种以最少的代码输出格式化时间的方法,因此这是我的解决方案。无论如何,许多人都使用熊猫,因此在某些情况下,可以从其他库导入中节省下来。

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

输出:

0 days 00:05:32.541600

如果时间精度不是最重要的,我建议使用此方法,否则请使用time库:

%timeit pd.Timestamp.now() 每个回路输出3.29 µs±214 ns

%timeit time.time() 每个回路输出154 ns±13.3 ns

I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

import pandas as pd
start = pd.Timestamp.now()
# code
print(pd.Timestamp.now()-start)

Output:

0 days 00:05:32.541600

I would recommend using this if time precision is not the most important, otherwise use time library:

%timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

%timeit time.time() outputs 154 ns ± 13.3 ns per loop


回答 5

将代码放入函数中,然后使用装饰器进行计时是另一种选择。()此方法的优点是您只需定义一次计时器,并将其与每个功能的附加简单行一起使用。

首先,定义timer装饰器:

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

然后,在定义函数时使用装饰器:

@timer
def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

我们试试吧:

doubled_and_add(100000)
doubled_and_add(1000000)

输出:

Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

注意:我不确定为什么要使用time.perf_counter而不是time.time。欢迎发表评论。

Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.

First, define timer decorator:

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

Then, use the decorator while defining the function:

@timer
def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

Let’s try:

doubled_and_add(100000)
doubled_and_add(1000000)

Output:

Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

Note: I’m not sure why to use time.perf_counter instead of time.time. Comments are welcome.


回答 6

您也可以尝试以下方法:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

You can try this as well:

from time import perf_counter

t0 = perf_counter()

...

t1 = perf_counter()
time_taken = t1 - t0

如何计算两个时间字符串之间的时间间隔

问题:如何计算两个时间字符串之间的时间间隔

我有两次,开始时间和停止时间,格式为10:33:26(HH:MM:SS)。我需要两次之间的区别。我一直在浏览Python文档并在线搜索,我想这可能与datetime和/或time模块有关。我无法使其正常工作,并且仅在涉及约会时才继续寻找如何执行此操作。

最终,我需要计算多个持续时间的平均值。我得到了可以工作的时差,并将它们存储在列表中。我现在需要计算平均值。我正在使用正则表达式解析原始时间,然后进行区别。

对于平均,我应该转换为秒然后平均吗?

I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I’ve been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can’t get it to work properly and keep finding only how to do this when a date is involved.

Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I’m storing them in a list. I now need to calculate the average. I’m using regular expressions to parse out the original times and then doing the differences.

For the averaging, should I convert to seconds and then average?


回答 0

是的,datetime这里绝对是您所需要的。具体来说,是strptime将字符串解析为时间对象的函数。

from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

这样就得到了一个timedelta包含两次差异的对象。您可以执行此操作,例如将其转换为秒或将其添加到另一个datetime

如果结束时间早于开始时间,则返回否定结果,例如s1 = 12:00:00s2 = 05:00:00。如果在这种情况下,如果您希望代码假定间隔经过午夜(即应该假定结束时间永远不会早于开始时间),则可以在上面的代码中添加以下几行:

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

(当然,您需要在from datetime import timedelta某处添加)。感谢JF Sebastian指出了这个用例。

Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object.

from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.

This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.


回答 1

尝试一下-在安排短期事件时非常有效。如果花费了一个多小时,那么最终的显示可能会需要一些友好的格式。

import time
start = time.time()

time.sleep(10)  # or do something more productive

done = time.time()
elapsed = done - start
print(elapsed)

返回时差作为经过的秒数。

Try this — it’s efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.

import time
start = time.time()

time.sleep(10)  # or do something more productive

done = time.time()
elapsed = done - start
print(elapsed)

The time difference is returned as the number of elapsed seconds.


回答 2

即使结束时间小于开始时间(超过午夜间隔),例如23:55:00-00:25:00(半小时),这也是一种支持找到差异的解决方案:

#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta

def time_diff(start, end):
    if isinstance(start, datetime_time): # convert to datetime
        assert isinstance(end, datetime_time)
        start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
    if start <= end: # e.g., 10:33:26-11:15:49
        return end - start
    else: # end < start e.g., 23:55:00-00:25:00
        end += timedelta(1) # +day
        assert end > start
        return end - start

for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
    s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
    print(time_diff(s, e))
    assert time_diff(s, e) == time_diff(s.time(), e.time())

输出量

0:42:23
0:30:00

time_diff()返回一个timedelta对象,您可以将其直接(作为序列的一部分)传递给mean()函数,例如:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

mean()结果也是timedelta()对象,可转换为秒(td.total_seconds()方法(因为Python 2.7)),小时(td / timedelta(hours=1)(Python 3中)),等等。

Here’s a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):

#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta

def time_diff(start, end):
    if isinstance(start, datetime_time): # convert to datetime
        assert isinstance(end, datetime_time)
        start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
    if start <= end: # e.g., 10:33:26-11:15:49
        return end - start
    else: # end < start e.g., 23:55:00-00:25:00
        end += timedelta(1) # +day
        assert end > start
        return end - start

for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
    s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
    print(time_diff(s, e))
    assert time_diff(s, e) == time_diff(s.time(), e.time())

Output

0:42:23
0:30:00

time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.


回答 3

表示Python中时差的结构称为timedelta。如果有start_timeend_time作为datetime类型,则可以使用以下-运算符来计算差异:

diff = end_time - start_time

您应该在转换为特定的字符串格式之前执行此操作(例如,在start_time.strftime(…)之前)。如果您已经有了字符串表示形式,则需要使用strptime方法将其转换回时间/日期时间。

Structure that represent time difference in Python is called timedelta. If you have start_time and end_time as datetime types you can calculate the difference using - operator like:

diff = end_time - start_time

you should do this before converting to particualr string format (eg. before start_time.strftime(…)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.


回答 4

网站说尝试:

import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt) 
diff.seconds/60 

本论坛使用time.mktime()

This site says to try:

import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt) 
diff.seconds/60 

This forum uses time.mktime()


回答 5

我喜欢这个人的做法-https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps。不知道它是否有缺点。

但是对我来说看起来很整洁:)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

关于这个问题,您仍然需要datetime.strptime()像其他人所说的那样使用。

I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.

But looks neat for me :)

from datetime import datetime
from dateutil.relativedelta import relativedelta

t_a = datetime.now()
t_b = datetime.now()

def diff(t_a, t_b):
    t_diff = relativedelta(t_b, t_a)  # later/end time comes first!
    return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)

Regarding to the question you still need to use datetime.strptime() as others said earlier.


回答 6

试试这个

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

输出:

0:00:05

Try this

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

OUTPUT :

0:00:05

回答 7

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

结果:0 0 0 0 -47 -37

import datetime as dt
from dateutil.relativedelta import relativedelta

start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
    timedelta_obj.years,
    timedelta_obj.months,
    timedelta_obj.days,
    timedelta_obj.hours,
    timedelta_obj.minutes,
    timedelta_obj.seconds,
)

result: 0 0 0 0 -47 -37


回答 8

两者timedatetime都有日期部分。

通常,如果您只处理时间部分,则需要提供默认日期。如果您只是对两者之间的差异感兴趣,并且知道两个时间都在同一天,datetime则为每个日期构造一个a ,并将日期设置为今天,然后从停止时间中减去开始时间以获取时间间隔(timedelta)。

Both time and datetime have a date component.

Normally if you are just dealing with the time part you’d supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).


回答 9

看一下datetime模块和timedelta对象。您应该最终为开始时间和结束时间构造一个datetime对象,然后减去它们,您将获得一个timedelta。

Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.


回答 10

如果您只是对24小时以下的时间感兴趣,请简明扼要。您可以根据需要在return语句中格式化输出:

import datetime
def elapsed_interval(start,end):
    elapsed = end - start
    min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
    hour, minutes = divmod(min, 60)
    return '%.2d:%.2d:%.2d' % (hour,minutes,secs)

if __name__ == '__main__':
    time_start=datetime.datetime.now()
    """ do your process """
    time_end=datetime.datetime.now()
    total_time=elapsed_interval(time_start,time_end)

Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :

import datetime
def elapsed_interval(start,end):
    elapsed = end - start
    min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
    hour, minutes = divmod(min, 60)
    return '%.2d:%.2d:%.2d' % (hour,minutes,secs)

if __name__ == '__main__':
    time_start=datetime.datetime.now()
    """ do your process """
    time_end=datetime.datetime.now()
    total_time=elapsed_interval(time_start,time_end)

Python日志记录:使用毫秒格式的时间

问题:Python日志记录:使用毫秒格式的时间

默认情况下logging.Formatter('%(asctime)s'),使用以下格式打印:

2011-06-09 10:54:40,638

其中638是毫秒。我需要将逗号更改为点:

2011-06-09 10:54:40.638

要格式化时间,我可以使用:

logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)

但是,文档未指定如何设置毫秒格式。我发现这太问题,其中约微秒的会谈,但)我宁愿毫秒和b)下列不上的Python 2.6(其中我的工作),由于工作的关系%f

logging.Formatter(fmt='%(asctime)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')

By default logging.Formatter('%(asctime)s') prints with the following format:

2011-06-09 10:54:40,638

where 638 is the millisecond. I need to change the comma to a dot:

2011-06-09 10:54:40.638

To format the time I can use:

logging.Formatter(fmt='%(asctime)s',datestr=date_format_str)

however the documentation doesn’t specify how to format milliseconds. I’ve found this SO question which talks about microseconds, but a) I would prefer milliseconds and b) the following doesn’t work on Python 2.6 (which I’m working on) due to the %f:

logging.Formatter(fmt='%(asctime)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')

回答 0

请注意,克雷格·麦克丹尼尔(Craig McDaniel)的解决方案显然更好。


logging.Formatter的formatTime方法如下所示:

def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

请注意中的逗号"%s,%03d"。不能通过指定a来解决此问题,datefmt因为cta是,time.struct_time并且这些对象不记录毫秒。

如果我们更改的定义ct以使其成为datetime对象而不是struct_time,那么(至少在现代版本的Python中)可以调用ct.strftime,然后可以用来%f设置微秒的格式:

import logging
import datetime as dt

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s,%03d" % (t, record.msecs)
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

或者,要获取毫秒数,请将逗号更改为小数点,然后省略datefmt参数:

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s.%03d" % (t, record.msecs)
        return s

...
formatter = MyFormatter(fmt='%(asctime)s %(message)s')
...
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.

Please note Craig McDaniel’s solution is clearly better.


logging.Formatter’s formatTime method looks like this:

def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

Notice the comma in "%s,%03d". This can not be fixed by specifying a datefmt because ct is a time.struct_time and these objects do not record milliseconds.

If we change the definition of ct to make it a datetime object instead of a struct_time, then (at least with modern versions of Python) we can call ct.strftime and then we can use %f to format microseconds:

import logging
import datetime as dt

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s,%03d" % (t, record.msecs)
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

Or, to get milliseconds, change the comma to a decimal point, and omit the datefmt argument:

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s.%03d" % (t, record.msecs)
        return s

...
formatter = MyFormatter(fmt='%(asctime)s %(message)s')
...
logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09 08:14:38.343 Jackdaws love my big sphinx of quartz.

回答 1

这也应该工作:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')

This should work too:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')

回答 2

添加毫秒是更好的选择,谢谢。这是我在Blender中将其与Python 3.5.3结合使用的修正

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")

Adding msecs was the better option, Thanks. Here is my amendment using this with Python 3.5.3 in Blender

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
log = logging.getLogger(__name__)
log.info("Logging Info")
log.debug("Logging Debug")

回答 3

我发现的最简单的方法是覆盖default_msec_format:

formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'

The simplest way I found was to override default_msec_format:

formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'

回答 4

实例化后,Formatter我通常会设置formatter.converter = gmtime。因此,在这种情况下,为了使@unutbu的答案起作用,您需要:

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s.%03d" % (t, record.msecs)
        return s

After instantiating a Formatter I usually set formatter.converter = gmtime. So in order for @unutbu’s answer to work in this case you’ll need:

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s.%03d" % (t, record.msecs)
        return s

回答 5

一个不需要datetime模块且不受其他解决方案限制的简单扩展就是使用简单的字符串替换,如下所示:

import logging
import time

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        if "%F" in datefmt:
            msec = "%03d" % record.msecs
            datefmt = datefmt.replace("%F", msec)
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

这样,可以使用%F毫秒来编写所需的日期格式,甚至允许区域差异。例如:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

sh = logging.StreamHandler()
log.addHandler(sh)

fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)

log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz

A simple expansion that doesn’t require the datetime module and isn’t handicapped like some other solutions is to use simple string replacement like so:

import logging
import time

class MyFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
    ct = self.converter(record.created)
    if datefmt:
        if "%F" in datefmt:
            msec = "%03d" % record.msecs
            datefmt = datefmt.replace("%F", msec)
        s = time.strftime(datefmt, ct)
    else:
        t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
        s = "%s,%03d" % (t, record.msecs)
    return s

This way a date format can be written however you want, even allowing for region differences, by using %F for milliseconds. For example:

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

sh = logging.StreamHandler()
log.addHandler(sh)

fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)

log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz

回答 6

如果您使用箭头,或者您不介意使用箭头。您可以将python的时间格式替换为arrow的时间格式。

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

现在,您可以在属性中使用所有箭头的时间格式datefmt

If you are using arrow or if you don’t mind using arrow. You can substitute python’s time formatting for arrow’s one.

import logging

from arrow.arrow import Arrow


class ArrowTimeFormatter(logging.Formatter):

    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)


logger = logging.getLogger(__name__)

default_handler = logging.StreamHandler()
default_handler.setFormatter(ArrowTimeFormatter(
    fmt='%(asctime)s',
    datefmt='YYYY-MM-DD HH:mm:ss.SSS'
))

logger.setLevel(logging.DEBUG)
logger.addHandler(default_handler)

Now you can use all of arrow’s time formatting in datefmt attribute.


回答 7

tl; dr供在此处查找ISO格式日期的人员使用:

datefmt:’%Y-%m-%d%H:%M:%S.%03d%z’

tl;dr for folks looking here for an ISO formatted date:

instead of using something like ‘%Y-%m-%d %H:%M:%S.%03d%z’, create your own class as @unutbu indicated. Here’s one for iso date format:

import logging
from time import gmtime, strftime

class ISOFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
        z = strftime("%z",gmtime(record.created))
        s = "%s.%03d%s" % (t, record.msecs,z)        
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.


回答 8

到目前为止,以下与python 3完美兼容。

         logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)-8s %(message)s',
                     datefmt='%Y/%m/%d %H:%M:%S.%03d',
                     filename=self.log_filepath,
                     filemode='w')

提供以下输出

2020/01/11 18:51:19.011信息

As of now the following works perfectly with python 3 .

         logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)-8s %(message)s',
                     datefmt='%Y/%m/%d %H:%M:%S.%03d',
                     filename=self.log_filepath,
                     filemode='w')

gives the following output

2020/01/11 18:51:19.011 INFO


如何从gmtime()的时间+日期输出获取自纪元以来的秒数?

问题:如何从gmtime()的时间+日期输出获取自纪元以来的秒数?

你如何做相反gmtime(),你把时间+日期,并获得秒数?

我有类似的字符串'Jul 9, 2009 @ 20:02:58 UTC',并且我想获取从纪元到2009年7月9日之间的秒数。

我已经尝试过,time.strftime但是我不知道如何正确使用它,或者它是否是正确的命令。

How do you do reverse gmtime(), where you put the time + date and get the number of seconds?

I have strings like 'Jul 9, 2009 @ 20:02:58 UTC', and I want to get back the number of seconds between the epoch and July 9, 2009.

I have tried time.strftime but I don’t know how to use it properly, or if it is the correct command to use.


回答 0

如果您是由于搜索引擎告诉您这是获取Unix时间戳的方法而到达此处的,请停止阅读此答案。向下滚动一个。

如果想扭转time.gmtime(),那就想calendar.timegm()

>>> calendar.timegm(time.gmtime())
1293581619.0

您可以使用将字符串转换为时间元组time.strptime(),该时间元组返回一个时间元组,您可以将其传递给calendar.timegm()

>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778

有关日历模块的更多信息,请点击此处

If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll down one.

If you want to reverse time.gmtime(), you want calendar.timegm().

>>> calendar.timegm(time.gmtime())
1293581619.0

You can turn your string into a time tuple with time.strptime(), which returns a time tuple that you can pass to calendar.timegm():

>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778

More information about calendar module here


回答 1

使用时间模块:

epoch_time = int(time.time())

Use the time module:

epoch_time = int(time.time())

回答 2

请注意,time.gmtime将时间戳映射01970-1-1 00:00:00

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) 给您一个时间戳,偏移的时间取决于您的语言环境,通常可能不为0。

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

与之相反的time.gmtimecalendar.timegm

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

Note that time.gmtime maps timestamp 0 to 1970-1-1 00:00:00.

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

The inverse of time.gmtime is calendar.timegm:

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

回答 3

ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()

这应该与有所不同int(time.time()),但是可以安全地使用类似x % (60*60*24)

datetime-基本日期和时间类型:

与时间模块不同,日期时间模块不支持leap秒。

ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()

This should be different from int(time.time()), but it is safe to use something like x % (60*60*24)

datetime — Basic date and time types:

Unlike the time module, the datetime module does not support leap seconds.


回答 4

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

回答 5

有两种方法,具体取决于您的原始时间戳记:

mktime()timegm()

http://docs.python.org/library/time.html

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html


如何在python中将小时添加到当前时间

问题:如何在python中将小时添加到当前时间

我可以得到如下的当前时间:

from datetime import datetime
str(datetime.now())[11:19]

结果

'19:43:20'

现在,我正在尝试增加9 hours上述时间,如何在Python中为当前时间增加几个小时?

I am able to get the current time as below:

from datetime import datetime
str(datetime.now())[11:19]

Result

'19:43:20'

Now, i am trying to add 9 hours to the above time, how can I add hours to current time in Python?


回答 0

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

然后使用字符串格式获取相关内容:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

如果仅格式化日期时间,则可以使用:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

或者,正如@eumiro在评论中指出的那样- strftime

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you’re only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments – strftime


回答 1

导入日期时间和时间增量

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

但是更好的方法是:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

您可以通过引用strptimestrftime行为来更好地了解python如何处理日期和时间字段

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field


如何删除列表中的最后一项?

问题:如何删除列表中的最后一项?

我有这个程序来计算回答一个特定问题所花费的时间,并在回答不正确时退出while循环,但是我想删除上一次计算,所以我可以打电话min(),这不是错误的时间,抱歉这令人困惑。

from time import time

q = input('What do you want to type? ')
a = ' '
record = []
while a != '':
    start = time()
    a = input('Type: ')
    end = time()
    v = end-start
    record.append(v)
    if a == q:
        print('Time taken to type name: {:.2f}'.format(v))
    else:
        break
for i in record:
    print('{:.2f} seconds.'.format(i))

I have this program that calculates the time taken to answer a specific question, and quits out of the while loop when answer is incorrect, but i want to delete the last calculation, so i can call min() and it not be the wrong time, sorry if this is confusing.

from time import time

q = input('What do you want to type? ')
a = ' '
record = []
while a != '':
    start = time()
    a = input('Type: ')
    end = time()
    v = end-start
    record.append(v)
    if a == q:
        print('Time taken to type name: {:.2f}'.format(v))
    else:
        break
for i in record:
    print('{:.2f} seconds.'.format(i))

回答 0

如果我正确理解了问题,则可以使用切片符号保留除最后一项以外的所有内容:

record = record[:-1]

但是更好的方法是直接删除该项目:

del record[-1]

注意1:请注意,使用record = record [:-1]并不会真正删除最后一个元素,而是将子列表分配给record。如果您在函数中运行它并且record是参数,则这会有所不同。使用record = record [:-1]时,原始列表(函数外部)保持不变,而使用del record [-1]或record.pop()时,列表将更改。(如@pltrdy在评论中所述)

注意2:代码可以使用一些Python惯用法。我强烈建议您阅读:
像Pythonista一样的代码:惯用的Python(通过Wayback机器档案)。

If I understood the question correctly, you can use the slicing notation to keep everything except the last item:

record = record[:-1]

But a better way is to delete the item directly:

del record[-1]

Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)

Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).


回答 1

你应该用这个

del record[-1]

问题所在

record = record[:-1]

是因为它每次删除项目时都会复制列表,所以效率不是很高

you should use this

del record[-1]

The problem with

record = record[:-1]

Is that it makes a copy of the list every time you remove an item, so isn’t very efficient


回答 2

list.pop() 删除并返回列表的最后一个元素。

list.pop() removes and returns the last element of the list.


回答 3

你需要:

record = record[:-1]

for循环之前。

这将设置record为当前record列表,但没有最后一项。您可能会根据自己的需要,在执行此操作之前确保列表不为空。

You need:

record = record[:-1]

before the for loop.

This will set record to the current record list but without the last item. You may, depending on your needs, want to ensure the list isn’t empty before doing this.


回答 4

如果您在计时方面做得很多,我可以推荐这个小(20行)上下文管理器:

您的代码可能如下所示:

#!/usr/bin/env python
# coding: utf-8

from timer import Timer

if __name__ == '__main__':
    a, record = None, []
    while not a == '':
        with Timer() as t: # everything in the block will be timed
            a = input('Type: ')
        record.append(t.elapsed_s)
    # drop the last item (makes a copy of the list):
    record = record[:-1] 
    # or just delete it:
    # del record[-1]

仅供参考,以下是Timer上下文管理器的全部内容:

from timeit import default_timer

class Timer(object):
    """ A timer as a context manager. """

    def __init__(self):
        self.timer = default_timer
        # measures wall clock time, not CPU time!
        # On Unix systems, it corresponds to time.time
        # On Windows systems, it corresponds to time.clock

    def __enter__(self):
        self.start = self.timer() # measure start time
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.end = self.timer() # measure end time
        self.elapsed_s = self.end - self.start # elapsed time, in seconds
        self.elapsed_ms = self.elapsed_s * 1000  # elapsed time, in milliseconds

If you do a lot with timing, I can recommend this little (20 line) context manager:

You code could look like this then:

#!/usr/bin/env python
# coding: utf-8

from timer import Timer

if __name__ == '__main__':
    a, record = None, []
    while not a == '':
        with Timer() as t: # everything in the block will be timed
            a = input('Type: ')
        record.append(t.elapsed_s)
    # drop the last item (makes a copy of the list):
    record = record[:-1] 
    # or just delete it:
    # del record[-1]

Just for reference, here’s the content of the Timer context manager in full:

from timeit import default_timer

class Timer(object):
    """ A timer as a context manager. """

    def __init__(self):
        self.timer = default_timer
        # measures wall clock time, not CPU time!
        # On Unix systems, it corresponds to time.time
        # On Windows systems, it corresponds to time.clock

    def __enter__(self):
        self.start = self.timer() # measure start time
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.end = self.timer() # measure end time
        self.elapsed_s = self.end - self.start # elapsed time, in seconds
        self.elapsed_ms = self.elapsed_s * 1000  # elapsed time, in milliseconds

回答 5

只是list.pop() 现在就使用,如果您愿意,可以使用另一种方法:list.popleft()

just simply use list.pop() now if you want it the other way use : list.popleft()


回答 6

如果您有一个列表列表(在我的情况下为tracked_output_sheet),要在其中删除每个列表的最后一个元素,则可以使用以下代码:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

If you have a list of lists (tracked_output_sheet in my case), where you want to delete last element from each list, you can use the following code:

interim = []
for x in tracked_output_sheet:interim.append(x[:-1])
tracked_output_sheet= interim

如何使用python解析包含毫秒的时间字符串?

问题:如何使用python解析包含毫秒的时间字符串?

我能够用time.strptime解析包含日期/时间的字符串

>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)

如何解析包含毫秒的时间字符串?

>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
    data_string[found.end():])
ValueError: unconverted data remains: .123

I am able to parse strings containing date/time with time.strptime

>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)

How can I parse a time string that contains milliseconds?

>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
    data_string[found.end():])
ValueError: unconverted data remains: .123

回答 0

Python 2.6添加了一个新的strftime / strptime宏%f,该宏的执行时间为微秒。不知道这是否记录在任何地方。但是,如果您使用的是2.6或3.0,则可以执行以下操作:

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

编辑:我从来没有真正使用过该time模块,所以一开始我没有注意到这一点,但是看起来time.struct_time实际上并没有存储毫秒/微秒。最好使用datetime,例如:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you’re using 2.6 or 3.0, you can do this:

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

Edit: I never really work with the time module, so I didn’t notice this at first, but it appears that time.struct_time doesn’t actually store milliseconds/microseconds. You may be better off using datetime, like this:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

回答 1

我知道这是一个老问题,但是我仍在使用Python 2.4.3,我需要找到一种更好的方法将数据字符串转换为日期时间。

如果datetime不支持%f并且不需要try / except的解决方案是:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

这适用于输入字符串“ 2010-10-06 09:42:52.266000”

I know this is an older question but I’m still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.

The solution if datetime doesn’t support %f and without needing a try/except is:

    (dt, mSecs) = row[5].strip().split(".") 
    dt = datetime.datetime(*time.strptime(dt, "%Y-%m-%d %H:%M:%S")[0:6])
    mSeconds = datetime.timedelta(microseconds = int(mSecs))
    fullDateTime = dt + mSeconds 

This works for the input string “2010-10-06 09:42:52.266000”


回答 2

要给出nstehr的答案所引用的代码(从其来源):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

To give the code that nstehr’s answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

回答 3

上面的DNS答案实际上是不正确的。SO询问的时间是毫秒,但答案是毫秒。不幸的是,Python没有毫秒指令,只有毫秒(请参阅doc),但是您可以通过在字符串末尾附加三个零并将字符串解析为毫秒来解决该问题,例如:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

其中time_str的格式如下30/03/09 16:31:32.123

希望这可以帮助。

DNS answer above is actually incorrect. The SO is asking about milliseconds but the answer is for microseconds. Unfortunately, Python`s doesn’t have a directive for milliseconds, just microseconds (see doc), but you can workaround it by appending three zeros at the end of the string and parsing the string as microseconds, something like:

datetime.strptime(time_str + '000', '%d/%m/%y %H:%M:%S.%f')

where time_str is formatted like 30/03/09 16:31:32.123.

Hope this helps.


回答 4

我的第一个念头是尝试将其传递为“ 30/03/09 16:31:32.123”(在秒和毫秒之间使用句点而不是冒号)。但这没有用。快速浏览文档表明在任何情况下都将忽略小数秒…

啊,版本差异。据报道这是一个错误,现在在2.6+中,您可以使用“%S.%f”进行解析。

My first thought was to try passing it ’30/03/09 16:31:32.123′ (with a period instead of a colon between the seconds and the milliseconds.) But that didn’t work. A quick glance at the docs indicates that fractional seconds are ignored in any case…

Ah, version differences. This was reported as a bug and now in 2.6+ you can use “%S.%f” to parse it.


回答 5

从python邮件列表中:解析毫秒线程。尽管在作者的评论中提到,这有点像黑客,但其中张贴了一个似乎可以完成工作的功能。它使用正则表达式处理引发的异常,然后进行一些计算。

您还可以尝试先进行正则表达式和计算,然后再将其传递给strptime。

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author’s comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

You could also try do the regular expressions and calculations up front, before passing it to strptime.


回答 6

对于python 2我做到了

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

它打印时间“%H:%M:%S”,将time.time()拆分为两个子字符串(在。之前和之后。)xxxxxxx.xx,由于.xx是我的毫秒数,因此我将第二个子字符串添加到我的“% H:%M:%S“

希望有道理:)示例输出:

13:31:21.72闪烁01


13:31:21.81眨眼间01


13:31:26.3闪烁01


13:31:26.39眨眼间01


13:31:34.65起始车道01


For python 2 i did this

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

it prints time “%H:%M:%S” , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my “%H:%M:%S”

hope that makes sense :) Example output:

13:31:21.72 Blink 01


13:31:21.81 END OF BLINK 01


13:31:26.3 Blink 01


13:31:26.39 END OF BLINK 01


13:31:34.65 Starting Lane 01



如何检查两个日期之间的差异(以秒为单位)?

问题:如何检查两个日期之间的差异(以秒为单位)?

必须有一种更简单的方法来执行此操作。我有想要经常刷新的对象,因此我想记录它们的创建时间,对照当前时间戳进行检查,并根据需要刷新。

事实证明datetime.datetime很困难,我也不想深入ctime库。这样的事情有什么容易的吗?

There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary.

datetime.datetime has proven to be difficult, and I don’t want to dive into the ctime library. Is there anything easier for this sort of thing?


回答 0

如果要计算两个已知日期之间的差异,请使用total_seconds以下方法:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0

if you want to compute differences between two known dates, use total_seconds like this:

import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0


回答 1

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

那对你有用吗?

import time  
current = time.time()

...job...
end = time.time()
diff = end - current

would that work for you?


回答 2

>>> from datetime import datetime

>>>  a = datetime.now()

# wait a bit 
>>> b = datetime.now()

>>> d = b - a # yields a timedelta object
>>> d.seconds
7

(7将是您在上面等待的时间长短)

我发现datetime.datetime非常有用,因此,如果您遇到了复杂或尴尬的情况,请告诉我们。

编辑:感谢@WoLpH指出,人们不一定总是希望刷新得如此频繁,以至于日期时间会接近。通过考虑增量中的天数,您可以处理更长的时间戳差异:

>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800
>>> from datetime import datetime

>>>  a = datetime.now()

# wait a bit 
>>> b = datetime.now()

>>> d = b - a # yields a timedelta object
>>> d.seconds
7

(7 will be whatever amount of time you waited a bit above)

I find datetime.datetime to be fairly useful, so if there’s a complicated or awkward scenario that you’ve encountered, please let us know.

EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:

>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800

回答 3

我们在Python 2.7中提供了total_seconds()函数,请参见下面的python 2.6代码

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

回答 4

这是为我工作的人。

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

希望这可以帮助!

Here’s the one that is working for me.

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

Hope this helps!


在Python中,如何将自纪元以来的秒数转换为`datetime`对象?

问题:在Python中,如何将自纪元以来的秒数转换为`datetime`对象?

所述time模块可使用秒因为历元进行初始化:

>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, 
                 tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)

有没有一种优雅的方法可以datetime.datetime以相同的方式初始化对象?

The time module can be initialized using seconds since epoch:

>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, 
                 tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)

Is there an elegant way to initialize a datetime.datetime object in the same way?


回答 0

datetime.datetime.fromtimestamp 如果您知道时区的话,您将产生与相同的输出 time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

要么

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime

>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)

or

>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)

回答 1

纪元以来的秒数来datetimestrftime

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

Seconds since epoch to datetime to strftime:

>>> ts_epoch = 1362301382
>>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S')
>>> ts
'2013-03-03 01:03:02'

回答 2

从文档中,从纪元以来的几秒钟内获取时区感知日期时间对象的推荐方法是:

Python 3

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2,使用pytz

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:

Python 3:

from datetime import datetime, timezone
datetime.fromtimestamp(timestamp, timezone.utc)

Python 2, using pytz:

from datetime import datetime
import pytz
datetime.fromtimestamp(timestamp, pytz.utc)

回答 3

请注意,datetime.datetime。fromtimestamp(时间戳)和。utcfromtimestamp(时间戳)在1970年1月1日之前的日期上在Windows上失败,而负的unix时间戳似乎在基于unix的平台上起作用。文档说:

如果时间戳不在平台C gmtime()函数支持的值范围内,则可能会引发ValueError。通常将其限制在1970年至2038年之间

另请参见Issue1646728

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038

See also Issue1646728