如何使用 Python 按比例分配日期
我有一个非常简单的图表组件,它在 x/y 轴上取整数。 我的问题是我需要在此图表上表示日期/浮点数。 所以我想我可以按比例分配日期。 换句话说,假设我有以下日期:01/01/2008、02/01/2008 和 31/12/2008。 该算法将返回 0、16.667 和 100(1 个月 = 16.667%)。
我尝试使用 Python 2.5 的 datetime
和 timedelta
类,但无法实现这一点。 我以为我可以使用刻度数,但我什至无法从 datetime
获取该信息。
知道如何用 Python 编写这个算法吗? 否则还有其他想法或算法吗?
I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would return 0, 16.667, and 100 (1 month = 16.667%).
I tried to play with the datetime
and timedelta
classes of Python 2.5 and I am unable to achieve this. I thought I could use the number of ticks, but I am not even able to get that info from datetime
.
Any idea how I could write this algorithm in Python? Otherwise, any other ideas or algorithms?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在处理日期,则可以使用方法 toordinal< /a>.
*16.67% 大约是一年中的两个月,因此 2 月 1 日的比例约为其中的一半。
If you're dealing with dates, then you can use the method toordinal.
*16.67% is about two months of a year, so the proportion for Feb 1 is about half of that.
将时间增量转换为数值相当容易。
选择纪元时间。 计算每个值相对于纪元的增量。 将 delta 转换为数值。 然后像平常一样映射数值。
转换是直接的。 就像是:
It's fairly easy to convert a timedelta into a numeric value.
Select an epoch time. Calculate deltas for every value relative to the epoch. Convert the delta's into a numeric value. Then map the numeric values as you normally would.
Conversion is straight forward. Something like:
我不知道我是否完全理解你想要做什么,但是你可以只处理自 UNIX 纪元以来的秒数,然后使用普通的旧减法来获得一个范围,你可以将其缩放到大小你的情节。
在处理过程中,map函数会为你处理这种情况。 http://processing.org/reference/map_.html 我相信你可以适应这是为了你的目的
I don't know if I fully understand what you are trying to do, but you can just deal with times as number of seconds since the UNIX epoch and then just use plain old subtraction to get a range that you can scale to the size of your plot.
In processing, the map function will handle this case for you. http://processing.org/reference/map_.html I'm sure you can adapt this for your purpose