使用datetime在Python中获取CSV日期

时间:2014-05-21 03:28:49

标签: python csv matplotlib

我正在尝试从csv文件中获取日期以绘制图表,并且很难获得用于比较数据的方法。日期的格式为MM / DD / YYYY HH:MM:SS。我已经努力寻找一种方法来执行这项任务好几天,但我的导师坚持使用在线资源而不是为我们的最终项目提供直接帮助。

我认为我需要使用for循环来创建'现在'变量,但我不知道如何比较现在'现在'之下的所有日期。变量。我也不知道如何在'然后'中插入参数。变量,因为now [n]在csv文件中给出了日期的第n个条目。

提前感谢您的帮助,我会尽量安排我的帖子,以便澄清!

"""
Demo of scatter plot with varying marker colors and sizes.
"""
import numpy as np
import matplotlib.pyplot as plt
import os.path
import random
import datetime
from datetime import timedelta
import time


# Load a numpy record array from yahoo csv data with fields date,
# open, close, volume, adj_close from the mpl-data/example directory.
# The record array stores python datetime.date as an object array in
# the date column
directory = os.path.dirname(os.path.abspath(__file__))
datafile = os.path.join(directory, 'v2vcomm.csv')
data = np.recfromcsv(datafile, delimiter=',', filling_values=np.nan, case_sensitive=True, deletechars='', replace_space=' ')

#start = datetime.datetime(np.data(data.date)


#datetime.datetime.time.strftime("%y-%m-%d-%H-%M")
time = data.date
now = time.replace('/', ' ').replace(':', ' ').split() #having problems turning this into a useable list. It outputs a list containing each individual date as a element, so it isn't helpful to me
then = datetime.datetime(int(now[2]), int(now[0]), int(now[1]), int(now[3]), int(now[4]), int(now[5])) #trying to input int values for each item in one date, but the formatting is tricky to me

length = len(np.diff(data.msg_id))

#these random values are from an earlier assignment, going to  eliminate them when I get datetime working
x= []
z= []
for v in range(1,length+1):
    x.append(random.randint(0,300))
    z.append(random.randint(1,100))
y = np.diff(data.msg_id)

count = 1




fig, ax = plt.subplots()
ax.scatter(x, y, c=z, s=30, alpha=0.5)

ax.set_xlabel(r'Total Time Elasped since  - Seconds (300=5 min)', fontsize=12)
ax.set_ylabel(r'Impediments', fontsize=12)
ax.set_title('Traffic Flow Impediment Frequency')

ax.grid(True)
fig.tight_layout()

plt.show()

1 个答案:

答案 0 :(得分:1)

可以比较Python的datedatetime个对象。

示例:

>>> from datetime import date
>>> d1 = date(2014, 05, 21)
>>> d2 = date(2014, 05, 20)
>>> d1 < d2
False
>>> d1
datetime.date(2014, 5, 21)
>>> d1 > d2
True

请参阅:datetime文档。

关于插入列表的第二个问题:

>>> xs = [0, 1, 2, 4]
>>> xs.insert(3, 3)
>>> xs
[0, 1, 2, 3, 4]

请参阅:help(list)pydoc list在命令行上)。