Python的分数秒 [英] Python fraction of seconds
问题描述
在datetime模块,datetime,time和timedelta类都具有最小的微秒分辨率:
>>>从datetime import datetime,timedelta
>>> now = datetime.now()
>>>现在
datetime.datetime(2009,12,4,23,3,27,343000)
>>> now.microsecond
343000
如果要以小数秒显示datetime,只需插入小数点和条带尾随零:
>>>现在.strftime(%Y-%m-%d%H:%M:%S.%f)。rstrip('0')
'2009-12-04 23:03:27.343'$日期时间和时间类仅接受整数输入,小时数,分钟和秒数必须介于0到59之间,而且微秒必须在0到999999之间。然而,timedelta类将接受分数的浮点值,并为您执行所有适当的模运算: code>>>> span = timedelta(seconds = 3662.567)
>>>> span
datetime.timedelta(0,3662,567000)
timedelta的基本组件是天,秒和微秒(0,3662,567000以上),但是构造函数也将接受毫秒,小时和数周。所有输入可以是整数或浮点(正或负)。所有参数都转换为基本单位,然后进行归一化,使得0 <=秒< 60和0 <=微秒1000000。
您可以将跨度添加或减少到日期时间或时间实例或另一个跨度。愚蠢的,你可以很容易地想出一些功能或类来做你想要的exaxtly。您可以使用timedelta实例相对于某些固定的日期时间进行所有日期/时间处理,例如 basetime = datetime(2000,1,1,0,0,0)
然后转换为日期时间或时间实例进行显示或存储。
What is the best way to handle portions of a second in Python? The datetime library is excellent, but as far as I can tell it cannot handle any unit less than a second.
In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds:
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2009, 12, 4, 23, 3, 27, 343000)
>>> now.microsecond
343000
if you want to display a datetime with fractional seconds, just insert a decimal point and strip trailing zeros:
>>> now.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')
'2009-12-04 23:03:27.343'
the datetime and time classes only accept integer input and hours, minutes and seconds must be between 0 to 59 and microseconds must be between 0 and 999999. The timedelta class, however, will accept floating point values with fractions and do all the proper modulo arithmetic for you:
>>> span = timedelta(seconds=3662.567)
>>> span
datetime.timedelta(0, 3662, 567000)
The basic components of timedelta are day, second and microsecond (0, 3662, 567000 above), but the constructor will also accept milliseconds, hours and weeks. All inputs may be integers or floats (positive or negative). All arguments are converted to the base units and then normalized so that 0 <= seconds < 60 and 0 <= microseconds < 1000000.
You can add or subtract the span to a datetime or time instance or to another span. Fool around with it, you can probably easily come up with some functions or classes to do exaxtly what you want. You could probably do all your date/time processing using timedelta instances relative to some fixed datetime, say basetime = datetime(2000,1,1,0,0,0)
, then convert to a datetime or time instance for display or storage.
这篇关于Python的分数秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!