处理时间,日期,时间增量

处理时间,日期,时间增量

问题描述:

我遇到了一个问题,我经常在工作中和时差上工作.到目前为止,我已经使用许多if语句解决了这个问题,但是这些语句很容易出错.在寻找更好的解决方案而又不浪费时间的情况下,我遇到了时间,日期和时间差.但是这些对我来说似乎太死板了,因此我正在寻找有关如何使用python内置函数解决此问题的想法和技巧-如果可能的话.问题在于:将卫星数据从条带区合并到常规网格涉及许多简单的时间计算.如果我有日期整数:200702100700,我想从这样的时间格式中加上和减去小时和分钟,以使日期-18会给我一个考虑leap年的新日期,并且可以倒转跨年,年,月,日和转发.这是我对python的datetime包的了解:

I have a problem where I work a lot with time and time differences. So far I've solved this using many many if statements but these are error prone. In searching for a better solution and without reinventing the wheel, I came across time, date, and timedelta. But these seem too inflexible for me so I'm looking for ideas and tips on how to solve this problem using python's built-in functions - if possible. Here's the problem: Binning satellite data from swaths to regular grid involves lots of simple time calculations. If I have the date integer: 200702100700 I want to add and subtract hours and minutes from such a time format such that date - 18 would give me a new date that takes into account leap year and can go cross, year, month, day backwards and forwards. Here's what I understand of python's datetime package:

from datetime import timedelta, date, time
t1 = date(2007,01,01); t = time(12,0); t2 = datetime.combine(t1,t)
t3 = timedelta(hours=18); t4 = t2 - t3; t5 = t2 + t3
print t4
>>>datetime.timedelta(2006, 23401, 3001)

这一次在执行成千上万次计算的脚本中用处不大.我的问题是t4没有年,月或日的对象,而2006年似乎被视为小时.一切都很混乱.这可能在python/numpy/scipy中吗?如果是这样,有人可以给我小费吗?

This time is not very useable in a script that will do thousands of calculations. My problem is that t4 has no year, month, or day objects, and 2006 seems to be treated as hours. It's all very confusing. Is this possible in python/numpy/scipy? If so, can someone give me a tip?

Gerrat正确使用了datetime对象.

Gerrat got it right, use the datetime object.

您可以完全创建datetime对象,而无需分别创建日期和时间(或使用datetime.strptime()).

you can create the datetime object fully without creating date and time separately (or using datetime.strptime()).

BUG ALERT (BUG警报)

BUG ALERT Your code and some of the posted responses will inject a hard to see bug.

// this works
datetime(2007,01,01,12)
// this breaks
datetime(2007,01,09,12)

在python中,在代码中使用日期时,在"09"中键入"0"使其成为一个八进制数字("09"无效),请避免使用前导零.

In python, typing the "0" in "09" makes it an octal number ("09" is not valid) when using dates in in your code, avoid the leading zero.