Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中读取Excel格式的日期?_Python_Excel_Datetime - Fatal编程技术网

如何在Python中读取Excel格式的日期?

如何在Python中读取Excel格式的日期?,python,excel,datetime,Python,Excel,Datetime,如何将Excel日期(数字格式)转换为Python中的正确日期?您可以使用 从its中,您可以看到日期始终存储为数字;但是,可以使用将其转换为python日期 注意:PyPI上的版本似乎比xlrd网站上的版本更新得多。经过测试并等待几天的反馈后,我将在xlrd的xldate模块中提交以下全新功能。。。请注意,仍然运行Python2.1或2.2的顽固分子将无法使用它 ## # Convert an Excel number (presumed to represent a date, a date

如何将Excel日期(数字格式)转换为Python中的正确日期?

您可以使用

从its中,您可以看到日期始终存储为数字;但是,可以使用将其转换为python日期


注意:PyPI上的版本似乎比xlrd网站上的版本更新得多。

经过测试并等待几天的反馈后,我将在xlrd的xldate模块中提交以下全新功能。。。请注意,仍然运行Python2.1或2.2的顽固分子将无法使用它

##
# Convert an Excel number (presumed to represent a date, a datetime or a time) into
# a Python datetime.datetime
# @param xldate The Excel number
# @param datemode 0: 1900-based, 1: 1904-based.
# <br>WARNING: when using this function to
# interpret the contents of a workbook, you should pass in the Book.datemode
# attribute of that workbook. Whether
# the workbook has ever been anywhere near a Macintosh is irrelevant.
# @return a datetime.datetime object, to the nearest_second.
# <br>Special case: if 0.0 <= xldate < 1.0, it is assumed to represent a time;
# a datetime.time object will be returned.
# <br>Note: 1904-01-01 is not regarded as a valid date in the datemode 1 system; its "serial number"
# is zero.
# @throws XLDateNegative xldate < 0.00
# @throws XLDateAmbiguous The 1900 leap-year problem (datemode == 0 and 1.0 <= xldate < 61.0)
# @throws XLDateTooLarge Gregorian year 10000 or later
# @throws XLDateBadDatemode datemode arg is neither 0 nor 1
# @throws XLDateError Covers the 4 specific errors

def xldate_as_datetime(xldate, datemode):
    if datemode not in (0, 1):
        raise XLDateBadDatemode(datemode)
    if xldate == 0.00:
        return datetime.time(0, 0, 0)
    if xldate < 0.00:
        raise XLDateNegative(xldate)
    xldays = int(xldate)
    frac = xldate - xldays
    seconds = int(round(frac * 86400.0))
    assert 0 <= seconds <= 86400
    if seconds == 86400:
        seconds = 0
        xldays += 1
    if xldays >= _XLDAYS_TOO_LARGE[datemode]:
        raise XLDateTooLarge(xldate)

    if xldays == 0:
        # second = seconds % 60; minutes = seconds // 60
        minutes, second = divmod(seconds, 60)
        # minute = minutes % 60; hour    = minutes // 60
        hour, minute = divmod(minutes, 60)
        return datetime.time(hour, minute, second)

    if xldays < 61 and datemode == 0:
        raise XLDateAmbiguous(xldate)

    return (
        datetime.datetime.fromordinal(xldays + 693594 + 1462 * datemode)
        + datetime.timedelta(seconds=seconds)
        )
##
#将Excel数字(假定表示日期、日期时间或时间)转换为
#Python的datetime.datetime
#@param xldate Excel编号
#@param datemode 0:1900为基础,1:1904为基础。
#
警告:当使用此功能 #解释工作簿的内容时,应以Book.datemode传递 #该工作簿的属性。是否 #这本工作簿曾经在苹果电脑附近的任何地方都是无关紧要的。 #@返回一个datetime.datetime对象,精确到\u秒。
#
特殊情况:如果0.0这是裸指关节无安全带使用风险版本:

import datetime

def minimalist_xldate_as_datetime(xldate, datemode):
    # datemode: 0 for 1900-based, 1 for 1904-based
    return (
        datetime.datetime(1899, 12, 30)
        + datetime.timedelta(days=xldate + 1462 * datemode)
        )
对于快速和肮脏:

year, month, day, hour, minute, second = xlrd.xldate_as_tuple(excelDate, wb.datemode)
whatYouWant = str(month)+'/'+str(day)+'/'+str(year)

请参阅此链接:

这对我很有用:

在该快照中,链接具有:

import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime

xlrd.xldate\u as_tuple
很好,但也有
xlrd.xldate.xldate\u as_datetime
转换为datetime

import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)

一组人的帖子给了我excel转换的日期和时间。我确实把它作为字符串返回了

def xldate_to_datetime(xldate):
  tempDate = datetime.datetime(1900, 1, 1)
  deltaDays = datetime.timedelta(days=int(xldate))
  secs = (int((xldate%1)*86400)-60)
  detlaSeconds = datetime.timedelta(seconds=secs)
  TheTime = (tempDate + deltaDays + detlaSeconds )
  return TheTime.strftime("%Y-%m-%d %H:%M:%S")

将excel文件转换为CSV时,日期/时间单元格如下所示:

foo,3/16/2016 10:38,酒吧

要将datetime文本值转换为datetime python对象,请执行以下操作:

from datetime import datetime

date_object = datetime.strptime('3/16/2016 10:38', '%m/%d/%Y %H:%M')    # excel format (CSV file)

打印日期对象将返回2005-06-01 13:33:00

如果您正在使用pandas,并且您的read\u excel读入的日期格式不正确,并且需要恢复后面的实际日期

列上应用的
lambda函数
使用xlrd恢复日期

import xlrd
df['possible_intdate'] = df['possible_intdate'].apply(lambda s: xlrd.xldate.xldate_as_datetime(s, 0))


>> df['possible_intdate']

   dtype('<M8[ns]')
导入xlrd
df['apability_intdate']=df['apability_intdate'].apply(lambda s:xlrd.xldate.xldate_as_datetime(s,0))
>>df[“可能的输入日期”]
数据类型('预期情况

# Wrong output from cell_values()
42884.0

# Expected output
2017-5-29
示例:让来自页码0的单元格\u值(2,2)作为日期 目标

获取所需的变量,如下所示

workbook = xlrd.open_workbook("target.xlsx")

sheet = workbook.sheet_by_index(0)

wrongValue = sheet.cell_value(2,2)
并使用xldate\u作为元组

y, m, d, h, i, s = xlrd.xldate_as_tuple(wrongValue, workbook.datemode)
print("{0} - {1} - {2}".format(y, m, d))

这是我的解决方案

因为您的excel文件可能来自不同的计算机/人;也可能格式混乱;所以要格外小心

我刚从50多个Excel导入了数据,其中日期是
DD/MM/yyyyy
DD-MM-YYYY
中输入的,但大多数Excel文件存储为
MM/DD/YYYY
(可能是因为电脑是用
en-us
而不是
en-gb
en-in

更令人恼火的是,上述日期仍采用
DD/MM/yyyyy
格式,因此Excel文件中存在差异

我找到的最可靠的解决方案是手动将每个excel文件上的日期列设置为纯文本,然后使用以下代码对其进行解析:

if date_str_from_excel:
    try:
        return datetime.strptime(date_str_from_excel, '%d/%m/%Y')
    except ValueError:
        print("Unable to parse date")

excel将日期和时间存储为一个数字,表示自1900年1月0日以来的天数,如果要使用python以日期格式获取日期,只需从“天数”列中减去2天,如下所示:

python中的Date=sheet.cell(1,0).value-2


在我的excel中的第1列,我有一个date and above命令,它给我的日期值减去2天,这与我的excel工作表中的日期相同,这是@hounded的修订版本。我的代码处理日期和时间,类似于43705.591795706

    import math
    import datetime


    def xldate_to_datetime(xldatetime): #something like 43705.6158241088

      tempDate = datetime.datetime(1899, 12, 31)
      (days, portion) = math.modf(xldatetime)

      deltaDays = datetime.timedelta(days=days)
      #changing the variable name in the edit
      secs = int(24 * 60 * 60 * portion)
      detlaSeconds = datetime.timedelta(seconds=secs)
      TheTime = (tempDate + deltaDays + detlaSeconds )
      return TheTime.strftime("%Y-%m-%d %H:%M:%S")


xldate_to_datetime(43705.6158241088)
# 2019-08-29 14:46:47

若你们在excel文件中有一个datetime列,那个么下面的代码将修复它。我在StackOverflow上查阅了很多答案,但都并没有修复它。我认为文件已经损坏了

from datetime import datetime
jsts = 1468629431.0
datetime.fromtimestamp(jsts) 

请澄清:举一个“Excel数据(数字格式)”的例子,Excel内部将日期存储为浮点数,您可以将其与“普通”区分开来“数字只能按单元格的格式存储。@Roberto Liffredo,是的,我知道Excel将日期存储为浮点数,我需要将它们转换为正确的日期,这就是我提出这个问题的原因。@eliben,请参阅Roberto的评论您可能还想在中查看答案。您好@JohnMachin很抱歉,要恢复一个旧线程,但您提交了吗?”。我使用的是Ubuntu和python 2.7,我使用的版本中没有它。从xlrd版本0.9.3(2014年4月发布给PyPI)开始,
xldate\u as\u datetime
函数被添加到
xldate
模块中.
xldate\u as\u datetime
是一个比我认为基于1900个Excel日期的
xldate\u as\u tuple
更干净的选项,对于1900年3月1日之前的Excel日期,这将给出不正确的
datetime
s。这是由于Excel中的一个错误导致的(错误)想想1900年是闰年。看看,还有一个非常像计算机科学的假设,由于某种原因,1900年的年初是1。好像是中世纪,我们不理解0的概念;为微软欢呼。@AER这不是微软的错,他们在实现Lotus 1时继承了这种疯狂23的datetime。另外,1中的大量语言索引,1中的大部分科学语言索引我希望我在这里没有做错什么,我只想在这里给出正确答案的方向。别担心!可能更适合将重复问题的链接作为对该问题的评论,但将其作为答案是错误的,至少对我来说,也可以。当然,从下次开始,我只会放置链接,不会复制答案,非常感谢。很好的例子,我刚刚添加了
strftime
,用于格式化
a1\u as\u datetime=datetime.datetime(*xlrd.xld