简体   繁体   English

使用Pandas在Python中解析日期

[英]Parsing dates in Python using Pandas

So my question is when I run this code for first time and it was giving me the results correctly ie in the format of 2013-01-23. 所以我的问题是,当我第一次运行此代码时,它正确地给了我结果,即格式为2013-01-23。

But when i tried running this code next time I was not getting the correct result (giving the output as 23/01/2013). 但是,当我下次尝试运行此代码时,没有得到正确的结果(给出的输出为23/01/2013)。

Why is it different the second time? 为什么第二次不一样?

from pandas import *
fec1 = read_csv("/user_home/w_andalib_dvpy/sample_data/sample.csv")

def convert_date(val):
    d, m, y = val.split('/')
    return datetime(int(y),int(m),int(d))

# FECHA is the date column name in raw file. format: 23/01/2013
fec1.FECHA.map(convert_date)
fec1.FECHA

Parsing dates with pandas can be done at the time you read the csv by passing parse_dates=['yourdatecolumn'] and date_parser=convert_date to the pandas.read_csv method . 通过将parse_dates=['yourdatecolumn']date_parser=convert_date传递给pandas.read_csv方法,可以在读取csv时完成使用pandas解析日期的pandas.read_csv

Doing it this way is a much faster operation than loading the data, then parsing the dates. 与加载数据然后解析日期相比,以这种方式进行操作要快得多。

The reason you get different outputs when you do the same operation twice is probably due to that when you parse the dates, you take D/M/Y as input, but have Y/M/D as output. 两次执行相同的操作时获得不同输出的原因可能是由于解析日期时,您将D / M / Y作为输入,而将Y / M / D作为输出。 it basically flips the D and Y every time. 它基本上每次都会翻转D和Y。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM