当前位置: 首页 > 知识库问答 >
问题:

从. txt文件Python读取日期的问题

裴俊迈
2023-03-14

我目前有一个脚本,在将csv文件转换为. txt后,我用它来绘制该文件的一部分。此时,它工作得很好,除了当我将第0列中的日期更改为序数形式时(我已经这样做了,所以我可以将所有值作为浮点数读取并在第4列上执行计算),Python去掉了小时、分钟和秒。我仍然需要小时和分钟,因为当我绘制数据时,它绘制了我在一天开始时的所有点。有没有一种方法可以做到这一点,并保持时间以及日期?我尝试过将日期转换成字符串,将另一列转换成浮点数,但这变得非常混乱。以下是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import csv
from numpy import ma

def skip_first(seq,n):
    for i, item in enumerate(seq):
        if i >= n:
            yield item
g = open('soundTransit1_remote_rawMeasurements_15m.txt', 'w')
with open('soundTransit1_remote_rawMeasurements_15m.dat', 'rb') as f:
    csvreader = csv.reader(f)
    for row in skip_first(csvreader,4):
        for row in csv.reader(f,delimiter=',',skipinitialspace=True):
            print >>g, "\t".join(row)
g.close()

def date2str(date_str):
    date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    return date.toordinal()

def readfiles(file_list):
    """ read <TAB> delemited files as strings
        ignoring '# Comment' lines """
    data = []
    for fname in file_list:
        data.append(
                    np.loadtxt(fname,
                               usecols=(0,4),
                               comments='#',    # skip comment lines
                               delimiter='\t',
                               converters = { 0 : date2str },
                               dtype=None))
    return data

data = readfiles(['soundTransit1_remote_rawMeasurements_15m.txt'])
data_1 = ma.fix_invalid(data, fill_value = 'nan')

column_0 = np.array(data_1)[0][:,0]
airTempRaw = np.array(data_1)[0][:,1]

#Compute Air Temperature
airTempRs_ohms = 23100*(airTempRaw/(1-airTempRaw))
airTemp_degC = -39.17*np.log(airTempRs_ohms) + 410.43

def init_plot(title, yMin=-10, yMax=40):
    plt.figure(figsize=(24, 12))
    plt.title(title + disclamers)
    plt.xlabel(xtext)
    plt.ylabel(ytext)
    #plt.xlim(xMin,xMax)
    plt.ylim(yMin,yMax)
    plt.grid()
    #plt.xticks(np.arange(xMin,xMax+1))

def end_plot(name=None, cols=5):
    plt.legend(bbox_to_anchor=(0, -.1, 1, -0.5), loc=8, ncol=cols,
               mode="expand", borderaxespad=-1.,  scatterpoints=1)
    if name:
        plt.savefig(name, bbox_inches='tight')

disclamers = ('\nUSGS PROVISIONAL DATA'
          '\nSUBJECT TO REVISION'
          )
xtext = ('Date & Time')
ytext = ('Air Temperature, deg C')

init_plot('Air Temperature')

plt.plot(column_0, airTemp_degC, linestyle='-', color='b', label='Air Temperature')

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d\n%H:%M'))
plt.gca().xaxis.set_minor_locator(mdates.HourLocator(interval=6))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1))

end_plot(name='py_airTemp.png')

提前感谢您的帮助!

共有1个答案

查学文
2023-03-14

你没有说日期列的格式是什么,但是我认为问题出在你的< code>np.loadtxt()中的转换器上。

从matplotlib查看此示例:http://matplotlib.org/examples/pylab_examples/load_converter.html?highlight=strpdate2num

我相信这应该行得通:

from matplotlib.dates import strpdate2num
def readfiles(file_list):
""" read <TAB> delemited files as strings
    ignoring '# Comment' lines """
data = []
for fname in file_list:
    data.append(
                np.loadtxt(fname,
                           usecols=(0,4),
                           comments='#',    # skip comment lines
                           delimiter='\t',
                           converters = { 0 : strpdate2num('%Y-%m-%d %H:%M:%S') },
                           dtype=None))
return data
 类似资料:
  • 我正在试着阅读我的文件的每一行,其中包含一个用户名列表,并用它创建一个登录系统。我正在尝试实现一个基本的登录系统,它的用户名存储在.txt文件中,但我的代码不工作,我不知道为什么。我认为问题出在检查用户名的循环中。 这是我的代码,但它不起作用,只是打印总是失败: 有什么想法吗?

  • 所以,我试图让我的程序从文本文件中读入一个结构数组,它编译得很好,但看起来并没有真正读入值?...我不知道为什么。这是代码的相关部分: 这是txt文件(标题:Planets.txt) 水星120 50 500 12.1 30 2金星120 50 500 29.1 30 6地球120 50 500 32.2 30 7月亮120 15 50 5.3 30 2火星120 50 500 12.2 30 4

  • 我的项目中有这样一段代码: 没有错误,应用程序运行正常,但是变量中从来没有任何文本,我确信txt文件中有文本! 我已经尝试过不同的方法来读取文本文件(使用BufferedReader、Scanner、FileInputStream和FileReader),但都不起作用。 另外,我几乎可以肯定问题不在变量中,因为我尝试通过代码(使用运行时)打开文件,它正常打开了正确的文件。 好的,我尝试添加,但是仍

  • 我正在学习NLTk,我需要加载一个大文件,我不想把它保存在我的桌面上。我怎么能用网站上托管的python读取文件? 我在这里尝试了这段代码,但它不起作用,我假设openwith是它的rson,但我需要使用openwith,因为在这种情况下我需要将它保存为file-myfile。 这就是错误: 如何在脚本中使用该文件而不下载整个文件? 我更改了代码以处理请求 但是现在当我运行这个我得到这个错误:

  • 本文向大家介绍Python3 解决读取中文文件txt编码的问题,包括了Python3 解决读取中文文件txt编码的问题的使用技巧和注意事项,需要的朋友参考一下 问题描述 尝试用Python写一个Wordcloud的时候,出现了编码问题。 照着网上某些博客的说法添添改改后,结果是变成了“UnicodeDecodeError: ‘utf-8' codec can't decode byte…”这个错误

  • 假设我有一个txt文件中的文本: bla bla bla bla bla bla 标题 Lorem ipsum dolor sat amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut laboure et dolore magna aliqua。 Ut enim ad minim veniam, 条件 bla