Python Pandas: how to set date format dd/mm/yyyy or dd.mm.yyyy and dtypes = datetime64

huangapple go评论77阅读模式
英文:

Python Pandas: how to set date format dd/mm/yyyy or dd.mm.yyyy and dtypes = datetime64

问题

df['Date'] = df['Date'].dt.strftime('%d/%m/%Y')  # 或者 df['Date'] = df['Date'].dt.strftime('%d.%m.%Y')
print(df.dtypes)
英文:

If I have a dataframe created from a csv file containing a column with date values (11.01.2023) how can I transform the column into a date format like dd/mm/yyyy (day 2 characters, month 2 characters, years 4 characters) or like dd.mm.yyyy? Thank you all

import pandas as pd

df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' }, 
                  'Price':{0:123, 1:456, 2:789}})
df

I tried:

import pandas as pd 
df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' }, 
                  'Price':{0:123, 1:456, 2:789}})

df['Date'].str.replace('.', '/', regex=False)
print(df.dtypes)    #    The Date column is object format


df['Date'] = pd.to_datetime(df['Date'], dayfirst=True) 
print(df.dtypes)    #   The Date column is format datetime64[ns]
print('df', df)     #   The date column is of the type yyyy-mm-dd

At this point how should I do to transform the Date column into a "dd/mm/yyyy"
or "dd.mm.yyyy" format and dtypes =datetime64 ?

See Image:

Python Pandas: how to set date format dd/mm/yyyy or dd.mm.yyyy and dtypes = datetime64

thank you all

答案1

得分: 1

这是一个难以回答的问题。这取决于您的用例。
如果您在笔记本环境中使用pandas,那么您应该使用一个样式器。以下是一个简短的示例解释它的工作原理:

import pandas as pd
from datetime import timedelta
from IPython.display import display

df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' }, 
                  'Price':{0:123, 1:456, 2:789}})
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

df_styler = df.style.format({'Date': lambda t: t.strftime("%m/%d/%Y")})
print(df.dtypes) # dtypes are not changed

print(df_styler) # printing a styler doesn't show the dataframe
print(df) # printing a dataframe this way does not involve the styler

display(df_styler) # this is how to render a dataframe with a styler

df['Date'] = df['Date'] + timedelta(days=5)

# the styler doesn't need to be remade if df changes
display(df_styler)

# in a notebook environment having a `df_styler` as the last
# command is equivalent to `display(df_styler)`
df_styler

如果您没有在笔记本环境中使用,并且/或者希望使用 print(df) 而不是将数据框呈现为HTML对象,则我不知道有什么好的解决方案。在这种情况下,我可能会编写自己的 print_df 函数,该函数会将 Date 列即时替换为使用 strftime 调用格式化的字符串列。

英文:

It is a deceptively hard question to answer. It depends on your use case.
If you are using pandas in a notebook environment, then you should use a styler. Here's a short example explaining how it works:

import pandas as pd
from datetime import timedelta
from IPython.display import display

df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' }, 
                  'Price':{0:123, 1:456, 2:789}})
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

df_styler = df.style.format({'Date': lambda t: t.strftime("%m/%d/%Y")})
print(df.dtypes) # dtypes are not changed

print(df_styler) # printing a styler doesn't show the dataframe
print(df) # printing a dataframe this way does not involve the styler

display(df_styler) # this is how to render a dataframe with a styler

df['Date'] = df['Date'] + timedelta(days=5)

# the styler doesn't need to be remade if df changes
display(df_styler)

# in a notebook environment having a `df_styler` as the last
# command is equivalent to `display(df_styler)`
df_styler

If you're not using a notebook environment, you can use df_styler.to_html() to get a formatted table in HTML.

if you are not in a notebook environment and/or want to use print(df) instead of rendering the dataframe as an HTML object, there is no good solution that I know of. What I would probably do in that case is write my own print_df function which would replace the Date column on the fly with a string column formatted with strftime call.

答案2

得分: 0

你可以使用strftime函数将datetime列格式化为特定的字符串格式。使用%d.%m.%Y格式字符串来使用.作为分隔符。

import pandas as pd

df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' },
                   'Price':{0:123, 1:456, 2:789}})

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

# 将datetime列格式化为"dd.mm.yyyy"格式
df['Date'] = df['Date'].dt.strftime('%d.%m.%Y')

print(df.dtypes)
print(df)

试试这个。
参考链接:https://www.geeksforgeeks.org/python-pandas-series-dt-strftime/

英文:

You can use the strftime function to format the datetime column into a specific string format. Use the . separator by using the %d.%m.%Y format string.

import pandas as pd

df = pd.DataFrame({'Date': {0: '11.01.2023 ', 1: '22.01.2023', 2: '08.02.2023' },
                   'Price':{0:123, 1:456, 2:789}})

df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

# Format the datetime column into "dd.mm.yyyy" format
df['Date'] = df['Date'].dt.strftime('%d.%m.%Y')

print(df.dtypes)
print(df)

Try this.
Reference: https://www.geeksforgeeks.org/python-pandas-series-dt-strftime/

huangapple
  • 本文由 发表于 2023年3月31日 16:37:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定