使用Python转换电子表格中的任何日期

使用Python转换电子表格中的任何日期

在这篇文章中,我们将看到如何使用Python转换电子表格中的任何日期。

使用的文件:

使用Python转换电子表格中的任何日期

这个文件包括一个题为 “日期 “的单列,并以一些不同形式的格式存储2021年的随机日期。

方法

  • 我们将从导入pandas库开始。
  • 让我们看一下转换日期的代码。

sample_dates[“Date”] = pd.to_datetime(sample_dates[“Date”]).dt.strftime(“%Y-%m-%d”)

  • 为了执行涉及日期和时间的任务,我们必须首先将该列转换为日期时间数据类型,这部分代码将这样做。

sample_dates[“Date”] = pd.to_datetime(sample_dates[“Date”])

  • 然后我们使用 dt 和 strftime 方法,其值为”%Y-%m-%d”,告知 Python 如何格式化日期。这里我们使用的例子是”%Y-%m-%”,其中%Y是全年,%m是2位数的月份,%d是2位数的日期。

示例 1:

转换电子表格中的任何日期

# This code converts any dates in spreadsheet
  
import pandas as pd
  
# Read the file and specify which column is the date
sample_dates = pd.read_excel("sample_dates.xlsx")
  
# Export output with dates converted to YYYY-MM-DD
sample_dates["Date"] = pd.to_datetime(
    sample_dates["Date"]).dt.strftime("%Y-%m-%d")
sample_dates.to_excel("sample_dates_formated.xlsx")
Python

输出:

使用Python转换电子表格中的任何日期

其他著名的格式。

示例日期 – 2021年12月18日,星期六,下午7:00

  • “%A, %B %d” -> “12月18日,星期六”
  • “%d-%b-%y” -> “18-Dec-21”
  • “%d/%m/%Y” -> “18/12/2021”
  • “%b %d, %Y” -> “2021年12月18日”
指令 意义 例子
%a 周日作为当地语言的缩写名称 Sun, Mon,…..,Sat(en_US); So, Mo,…..,Sa(de_DE)
%A 周日作为当地的全称 周日, 周一, ….., 周六
%w 工作日为十进制数字,其中0为星期日,6为星期六 0, 1, 2, 3……,6
%d 以零填充的十进制数字表示的月日 01,02,….31

示例 2:

我们将使用上一个例子中使用的相同的数据集。

Format - "%d %b, %Y" -> "18 December, 2021"
Python

在这里,我们将使用’%#d’来删除日期中的零的填充,即08到8。如果日期是个位数,这将不做零的填充。我们可以在Linux上使用’%-d’。

# This code converts any dates in spreadsheet
  
import pandas as pd
  
# Read the file and specify which column is 
# the date
sample_dates = pd.read_excel("sample_dates.xlsx")
  
# Export output with dates converted to 
# "D MMMM, YYYY"
sample_dates["Date"] = pd.to_datetime(
    sample_dates["Date"]).dt.strftime("%#d %B, %Y")
sample_dates.to_excel("sample_dates_formated.xlsx")
Python

输出:

使用Python转换电子表格中的任何日期

示例 3:

这里我们将使用不同的格式

Format - "%B %d, %Y" -> "December 18, 2021"
Python
# This code converts any dates in spreadsheet
  
import pandas as pd
  
# Read the file and specify which column is
# the date
sample_dates = pd.read_excel("sample_dates.xlsx")
  
# Export output with dates converted to "MMMM D, 
# YYYY"
sample_dates["Date"] = pd.to_datetime(
  sample_dates["Date"]).dt.strftime("%B %d, %Y")
sample_dates.to_excel("sample_dates_formated.xlsx")
Python

输出:

使用Python转换电子表格中的任何日期

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册