sourcetip

Python에서 Excel 형식의 날짜를 읽으려면 어떻게 해야 하나요?

fileupload 2023. 4. 23. 11:02
반응형

Python에서 Excel 형식의 날짜를 읽으려면 어떻게 해야 하나요?

Python에서 Excel 날짜(숫자 형식)를 적절한 날짜로 변환하려면 어떻게 해야 합니까?

xlrd를 사용할 수 있습니다.

문서에서 날짜는 항상 숫자로 저장되지만 를 사용하여 파이썬 날짜로 변환할 수 있습니다.

주의: PyPI의 버전은 xlrd 웹사이트에서 구할 수 있는 버전보다 더 최신인 것 같습니다.

다음은 맨몸으로 안전벨트를 착용할 수 있는 위험버전입니다.

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)
        )

테스트 후 피드백을 며칠 기다린 후 xlrd의 xldate 모듈에서 다음 완전히 새로운 기능을 커밋합니다.Python 2.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)
        )

xlrd.xldate_as_tuple좋긴 한데xlrd.xldate.xldate_as_datetime날짜/시간으로도 변환됩니다.

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

다음 링크를 참조하십시오: 날짜를 python xlrd를 사용하여 excel에서 뜨지 않는 문자열로 읽기

나한테는 효과가 있었어요.

이 링크에는 다음이 있습니다.

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

Excel 번호로 포맷된 날짜의 read_excel 읽기를 잘못 사용하여 실제 날짜를 복구해야 하는 경우...

lambda function컬럼에 적용된 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]')

예상되는 상황

# Wrong output from cell_values()
42884.0

# Expected output
2017-5-29

예: 시트 번호 0의 cell_values(2,2)를 대상 날짜로 합니다.

다음과 같이 필수 변수 가져오기

workbook = xlrd.open_workbook("target.xlsx")
 
sheet = workbook.sheet_by_index(0)

wrongValue = sheet.cell_value(2,2)

xldate_as_tuple을 사용합니다.

year, month, day, hour, minutes, seconds = xlrd.xldate_as_tuple(wrongValue, workbook.datemode)
print("{0} - {1} - {2}".format(year, month, day))

그것이 나의 해결책이다.

Excel 파일이 다른 컴퓨터/사람으로부터 전송되었을 가능성이 있기 때문에, 포맷이 복잡할 가능성이 있기 때문에, 특히 주의해 주세요.

날짜가 입력된 50개의 엑셀에서 데이터를 Import했습니다.DD/MM/YYYY또는DD-MM-YYYY그러나 대부분의 Excel 파일은 다음과 같이 저장됩니다.MM/DD/YYYY(아마도 PC는 다음과 같이 셋업되어 있을 것입니다.en-us대신en-gb또는en-in).

더 짜증나는 것은 위에서부터의 사실이었다.13/MM/YYYY있었다DD/MM/YYYY포맷은 그대로입니다.그래서 엑셀 파일에는 변형이 있었습니다.

가장 신뢰할 수 있는 솔루션은 각 Excel 파일의 [Date]컬럼을 수동으로 [Plain Text]로 설정하고 다음 코드를 사용하여 해석하는 것입니다.

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을 사용하여 날짜 형식으로 가져오려면 다음과 같이 days 열에서 2일을 빼기만 하면 됩니다.

날짜 = sheet.cell(1,0).value-2 //(python 단위)

Excel의 1열에 날짜 값에서 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

빠르고 더러운 경우:

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

people post의 조합으로 엑셀 전환 날짜와 시간을 알 수 있었습니다.끈으로 돌려주긴 했지만

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 파일에 datetime 열이 있는 경우.그러면 아래 코드가 수정될 것입니다.Stack Overflow에 대해 많은 답변을 검토했지만 아무것도 수정하지 않았습니다.파일이 손상된 줄 알았어요.

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

Excel 파일을 CSV로 변환할 때 날짜/시간 셀은 다음과 같습니다.

foo, 2016년 3월 16일 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)

print date_object는 2005-06-01 13:33:00를 반환합니다.

언급URL : https://stackoverflow.com/questions/1108428/how-do-i-read-a-date-in-excel-format-in-python

반응형