📌  相关文章
📜  如何在Python中将日期时间转换为日期

📅  最后修改于: 2022-05-13 01:55:33.003000             🧑  作者: Mango

如何在Python中将日期时间转换为日期

在本文中,我们将了解如何在Python中将 DateTime 转换为日期。为此,我们将使用 strptime() 方法。此方法用于从字符串创建 DateTime 对象。然后我们将使用 date()函数从 DateTime 对象中提取日期。

示例 1:将日期时间转换为日期。

在这个例子中,我们创建了一个 datetime_str,它是“24AUG2001101010” ,它的格式是“%d%b%Y%H%M%S”。



Python3
# import important module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "24AUG2001101010"
print("datetime string : {}".format(datetime_str))
  
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str, 
                                 "%d%b%Y%H%M%S")
  
# It will print the datetime object
print(datetime_obj)
  
# extract the time from datetime_obj
date = datetime_obj.date()
print(date)


Python3
# import important module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "100201095407"
print("datetime string : {}".format(datetime_str))
  
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str,
                                 "%d%m%y%H%M%S")
  
# It will print the datetime object
print(datetime_obj)
  
# extract the time from datetime_obj
date = datetime_obj.date()
  
# it will print date that we have
# extracted from datetime obj
print(date)


Python3
# import important module
from datetime import datetime
  
# call datetime.strptime to
# convert it into datetime datatype
datetime_obj = datetime.now()
  
# It will print the datetime object
print(datetime_obj)
  
# extract the time from datetime_obj
date = datetime_obj.date()
print(date)


输出 :

datetime string : 24AUG2001101010
2001-08-24 10:10:10
2001-08-24

示例 2:将日期时间转换为数字日期。

在这个例子中,我们创建了一个 datetime_str,它是“100201095407” ,它的格式是“%d%m%y%H%M%S”

蟒蛇3

# import important module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "100201095407"
print("datetime string : {}".format(datetime_str))
  
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str,
                                 "%d%m%y%H%M%S")
  
# It will print the datetime object
print(datetime_obj)
  
# extract the time from datetime_obj
date = datetime_obj.date()
  
# it will print date that we have
# extracted from datetime obj
print(date)

输出

datetime string : 100201095407
2001-02-10 09:54:07
2001-02-10

示例 3:将日期时间转换为当前日期。

在此示例中,我们获取当前日期和时间,并从对象中提取其日期。

蟒蛇3

# import important module
from datetime import datetime
  
# call datetime.strptime to
# convert it into datetime datatype
datetime_obj = datetime.now()
  
# It will print the datetime object
print(datetime_obj)
  
# extract the time from datetime_obj
date = datetime_obj.date()
print(date) 

输出:

2021-08-07 06:30:20.227879
2021-08-07