【问题标题】:Python: Compute Difference between Datetime Objects in a LoopPython:计算循环中日期时间对象之间的差异
【发布时间】:2016-03-10 21:18:54
【问题描述】:

使用 Python 2.7,我正在尝试创建一个相对时间数组,其中相对时间是雷暴中间时间与暴风雨期间其他时间之间的差异。最终,我希望我的相对时间数组的格式为 -minutes、0 和 +minutes(其中 -minutes 是风暴中间之前的分钟,0 是风暴中间,+minutes 是之后的分钟)暴风雨中)。我认为循环是最有效的方法。我已经有一个一维数组 MDAdatetime,其中填充了我提到的其他风暴时间,作为字符串。我在代码的开头指定了风暴的中间,它也是一个字符串。

到目前为止,我的代码如下:

import csv
import datetime

casedate = '06052009'
MDAfile = "/atmomounts/home/grad/mserino/Desktop/"+casedate+"MDA.csv"
stormmidpoint = '200906052226' #midpoint in YYYYMMDDhhmm
relativetime = []
MDAlons = []
MDAlats = []
MDAdatetime = []

with open(MDAfile, 'rU') as f: #open to read in universal-newline mode
reader = csv.reader(f, dialect=csv.excel, delimiter=',')
for i,row in enumerate(reader):
    if i == 0:
        continue #skip header row
    MDAlons.append(float(row[1]))
    MDAlats.append(float(row[2]))
    MDAdatetime.append(str(row[0])) #this is the array I'm dealing with now in the section below; each string is of the format YYYYMMDDhhmmss

## This is the section I'm having trouble with ##
for j in range(len(MDAdatetime)):
    reltime = datetime.datetime.strptime(MDAdatetime[j],'%YYYY%mm%dd%HH%MM%SS') - datetime.datetime(stormmidpoint,'%YYYY%mm%dd%HH%MM')
    retime.strftime('%MM') #convert the result to minutes
    reativetime.append(reltime)
print relativetime

到目前为止,我一直收到错误:

ValueError: time data '20090605212523' does not match format '%YYYY%mm%dd%HH%MM%SS'

我正在尝试尽可能多地了解 datetime 模块。我已经看到其他一些帖子和资源提到 dateutil,但似乎 datetime 对我来说是最有用的。不过,我可能是错的,我感谢任何建议和帮助。如果我需要澄清任何事情或提供更多信息,请告诉我。

【问题讨论】:

  • In [1]:这是偏好问题,但我很懒,使用 dateutil.parser:from dateutil.parser import parse as dateparsedateparse('200906052226') Out[1]:datetime.datetime(2009, 6, 5, 22, 26)

标签: python loops datetime math


【解决方案1】:

%Y 匹配 2016。不是%YYYY,月份、日期等类似。

所以,你的格式匹配器应该是%Y%m%d%H%M%S

类似这样的:

datetime.datetime.strptime("20090605212523", "%Y%m%d%H%M%S")

演示

>>> datetime.datetime.strptime("20090605212523", "%YYYY%mm%dd%HH%MM%SS")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '20090605212523' does not match format '%YYYY%mm%dd%HH%MM%SS'
>>> datetime.datetime.strptime("20090605212523", "%Y%m%d%H%M%S")
datetime.datetime(2009, 6, 5, 21, 25, 23)

【讨论】:

  • 好的,我做了那个改变,这很有帮助! (我不认为这会是一个如此简单的修复。)我还将我的stormmidpoint变量更改为一个整数,现在我得到了错误:OverflowError: signed integer is greater than maximum
  • 当我把它作为一个字符串,我得到错误:TypeError: must be string, not int
  • 那是不可能的。阅读消息。如果它是字符串,为什么它会说不是 int?仔细检查您的输入
  • 将 'stormmidpoint' 更改为字符串产生:reltime = datetime.datetime.strptime(MDAdatetime[j],'%Y%m%d%H%M%S') - datetime.datetime(stormmidpoint,'%Y%m%d%H%M') TypeError: an integer is required. 当我将其更改回整数时,我得到:reltime = datetime.datetime.strptime(MDAdatetime[j],'%Y%m%d%H%M%S') - datetime.datetime(stormmidpoint,'%Y%m%d%H%M') OverflowError: signed integer is greater than maximum. 抱歉,我在这里粘贴了不正确的错误。
【解决方案2】:

@karthikr 指出我的 strptime 格式不正确后,我能够在几分钟内成功获得答案。可能有更好的方法,但我在代码中手动转换为分钟。我还将我的stormmidpoint 变量更改为字符串,因为它应该是。 @karthikr 对此也是正确的。谢谢您的帮助!

for j in range(len(MDAdatetime)):
    reltime = datetime.datetime.strptime(MDAdatetime[j],'%Y%m%d%H%M%S') - datetime.datetime.strptime(stormmidpoint,'%Y%m%d%H%M%S')
    relativetime.append(int(math.ceil(((reltime.seconds/60.0) + (reltime.days*1440.0))))) #convert to integer minutes
print relativetime

【讨论】:

    猜你喜欢
    • 2010-11-07
    • 2021-11-25
    • 2011-08-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多