如何在 Pandas 数据框中将日期转换为 ISO-8601 DateTime 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18618288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:07:43  来源:igfitidea点击:

How do I convert dates into ISO-8601 DateTime format in a Pandas dataframe

pythondatepandas

提问by user7289

I have the dataframe below (using python/pandas) and wish to convert the

我有下面的数据框(使用 python/pandas)并希望转换

q_string          q_visits  q_date
red               1790  02/10/2012 00:00
blue              364   02/10/2012 00:00
current           280   02/10/2012 00:00
molecular         259   02/10/2012 00:00
cell              201   02/10/2012 00:00

How can I convert the 'q_date' field into SO-8601 DateTime format (yyyy-MM- ddTHH:mm:ssZ)?

如何将“q_date”字段转换为 SO-8601 日期时间格式 (yyyy-MM-ddTHH:mm:ssZ)?

Thanks in advance.

提前致谢。

回答by Viktor Kerkez

Use the pandas datetools parser to parse the date and then format it using the standard python strftimefunction.

使用pandas datetools 解析器解析日期,然后使用标准的pythonstrftime函数对其进行格式化。

>>> df['q_date'].apply(
        lambda x: pd.datetools.parse(x).strftime('%Y-%m-%dT%H:%M%:%SZ'))
0    20120210T00:0000Z
1    20120210T00:0000Z
2    20120210T00:0000Z
3    20120210T00:0000Z
4    20120210T00:0000Z
Name: q_date, dtype: object

回答by Casey Clements

I would use pd.to_datetimeand the .dt accessor

我会使用pd.to_datetime.dt accessor

pd.to_datetime(df['q_date']).dt.strftime('%Y-%m-%dT%H:%M%:%SZ')

回答by Phillip Cloud

First convert your q_datecolumn into a datetime64[ns]Series, then mapover the column with a custom format string

首先将您的q_date列转换为datetime64[ns]系列,然后map使用自定义格式字符串覆盖该列

In [178]: df = df.convert_objects(convert_dates='coerce')

In [179]: df
Out[179]:
    q_string  q_visits              q_date
0        red      1790 2012-02-10 00:00:00
1       blue       364 2012-02-10 00:00:00
2    current       280 2012-02-10 00:00:00
3  molecular       259 2012-02-10 00:00:00
4       cell       201 2012-02-10 00:00:00

In [180]: df['iso_q_date'] = df.q_date.map(lambda x: datetime.datetime.strftime(x, '%y%m%dT%H:%M%SZ'))

In [181]: df
Out[181]:
    q_string  q_visits              q_date       iso_q_date
0        red      1790 2012-02-10 00:00:00  120210T00:0000Z
1       blue       364 2012-02-10 00:00:00  120210T00:0000Z
2    current       280 2012-02-10 00:00:00  120210T00:0000Z
3  molecular       259 2012-02-10 00:00:00  120210T00:0000Z
4       cell       201 2012-02-10 00:00:00  120210T00:0000Z