简体   繁体   English

python - 如何转换日期序列

[英]python - how do I convert sequence in the dates

below is my dataframe with one column ie Date下面是我的 dataframe 一栏,即日期

df = pd.DataFrame({'Date' : ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09']})

assume that the dtype is datetime64[ns]假设 dtype 是 datetime64[ns]

I want to convert it to format %d-%m-%Y我想把它转换成格式 %d-%m-%Y

I used this formula我用这个公式

df['Date'].apply(lambda x: datetime.strptime(x.strftime("%d-%m-%Y"),"%d-%m-%Y"))

but the sequencing still didnt change - am I doing something wrong?但顺序仍然没有改变——我做错了什么吗?

df['Date'].apply(lambda x: datetime.strptime(x.strftime("%Y-%m-%d"),"%d-%m-%Y"))

Read it in the way it is, then print it the way you want it.按原样阅读,然后按您想要的方式打印。

Use dt.strftime :使用dt.strftime

df["Date"] = df["Date"].dt.strftime("%d-%m-%Y")

You example dataset doesn't have data of type datetime64[ns] , so lets convert them first您的示例数据集没有datetime64[ns]类型的数据,所以让我们先转换它们

Code代码

import pandas as pd
import datetime

# your dataset
df = pd.DataFrame({'Date': ['2014-03-27', '2014-03-28', '2014-03-31', '2014-04-01', '2014-04-02', '2014-04-03', '2014-04-04', '2014-04-07','2014-04-08', '2014-04-09']})

# convert to datetime64[ns] type
df['Date']=df['Date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d"))
print(df['Date'].dtype)

# convert to formatted string
df['Date']=df['Date'].apply(lambda x: x.strftime("%d-%m-%Y"))
print(df)

Output Output

datetime64[ns]

         Date
0  27-03-2014
1  28-03-2014
2  31-03-2014
3  01-04-2014
4  02-04-2014
5  03-04-2014
6  04-04-2014
7  07-04-2014
8  08-04-2014
9  09-04-2014

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

相关问题 如何在 Python 中将字符串转换为转义序列? - How do I convert a string to an escape sequence in Python? 当有两个日期时,如何从 Python 中的文件名中提取日期? 我如何转换为一年中的某一天? - How to extract dates from filename in Python when there are two dates? And how do I convert to day of year? 如何将相对日期转换为绝对日期? - How do I convert relative dates to absolute dates? Python 2-如何导入包含一长串数字的文本文件并将其转换为单个数字字符串? - Python 2 - How do I import a text file containing a long sequence of digits and convert it to a string of individual numbers? 在 Python 3.8.2 中,如何将包含 '\\uxxxx' 序列的字符串转换为 utf-8? - In Python 3.8.2, how do I convert a string that contains a '\uxxxx' sequence into utf-8? 如何在 Python 中编写一系列 Promise? - How do I write a sequence of promises in Python? 如何在Python中循环执行一系列功能? - How do I loop a sequence of functions in Python? 如何使用 Python 找到一系列值 - How do I find a sequence of values with Python 我如何识别序列方程 Python - how do I identify sequence equation Python 如何将python序列项转换为整数 - How do you convert a python sequence item to an integer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM