簡體   English   中英

使用Python將數字轉換為日期格式

[英]Convert number to date format using Python

我正在從具有14000多行的文本文件中讀取數據,並且其中有一列具有八(08)位數字。 一些行的格式如下:

  • 01021943
  • 02031944
  • 00041945
  • 00001946

問題是,當我使用to_date函數時,它將日期的數據類型從對象轉換為int64,但我希望它是datetime。 其次,使用to_datetime函數將日期

  • 00041945變為41945
  • 00001946變成1946,因此我無法正確格式化它們

您可以添加參數dtyperead_csv列轉換colstring ,然后使用to_datetime與參數format為指定的格式和errors='coerce' -因為壞的日期,被轉換到NaT

import pandas as pd
import io

temp=u"""col
01021943
02031944
00041945
00001946"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), dtype={'col': 'str'})

df['col'] = pd.to_datetime(df['col'], format='%d%m%Y', errors='coerce')

print (df)
         col
0 1943-02-01
1 1944-03-02
2        NaT
3        NaT

print (df.dtypes)
col    datetime64[ns]
dtype: object

感謝Jon Clements提供的另一種解決方案:

import pandas as pd
import io

temp=u"""col_name
01021943
02031944
00041945
00001946"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), 
                 converters={'col_name': lambda dt: pd.to_datetime(dt, format='%d%m%Y', errors='coerce')})

print (df)
    col_name
0 1943-02-01
1 1944-03-02
2        NaT
3        NaT

print (df.dtypes)
col_name    datetime64[ns]
dtype: object

作為第一個猜測的解決方案,您可以將其作為字符串解析為datetime實例。 就像是:

from datetime import datetime

EXAMPLE = u'01021943'

dt = datetime(int(EXAMPLE[4:]), int(EXAMPLE[2:4]), int(EXAMPLE[:2]))

...不太關心性能問題。

import datetime

def to_date(num_str):
    return datetime.datetime.strptime(num_str,"%d%m%Y")

請注意,這也會引發零值異常,因為此輸入的預期行為尚不清楚。
如果您希望零值具有不同的行為,則可以使用try & except實現它,
例如,如果您想獲得零值的None ,則可以執行以下操作:

def to_date(num_str):
    try:
        return datetime.datetime.strptime(num_str,"%d%m%Y")
    except ValueError, e:
        return None

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM