你可以使用datetime模块来将不同格式的日期转换为datetime格式。下面是一个示例函数,它可以将常见的日期格式转换为datetime格式:

from datetime import datetime

def convert_to_datetime(date_string):
    formats = ['%Y/%m/%d', '%Y年%m月%d日', '%Y-%m-%d', '%Y-%m-%d %H:%M:%S']
    for format in formats:
        try:
            datetime_obj = datetime.strptime(date_string, format)
            return datetime_obj
        except ValueError:
            pass
    raise ValueError('Invalid date format')

# 示例用法
date1 = '2023/4/4'
date2 = '2022年12月日'
date3 = '2023-4-4'
date4 = '2023-04-04 10:30:00'

datetime1 = convert_to_datetime(date1)
datetime2 = convert_to_datetime(date2)
datetime3 = convert_to_datetime(date3)
datetime4 = convert_to_datetime(date4)

print(datetime1)
print(datetime2)
print(datetime3)
print(datetime4)

这个函数首先定义了一系列常见的日期格式,然后使用strptime函数尝试将输入的日期字符串转换为datetime对象。如果能成功转换,则返回datetime对象;如果所有格式都不匹配,则抛出ValueError异常。

请注意,如果输入的日期格式与定义的格式不匹配,函数将会抛出ValueError异常。你可以根据自己的需求进行修改

python 把excel读到的各种日期格式包括202344、 2022年12月日、2023-4-4、日期戳转换成datetime格式的函数

原文地址: https://www.cveoy.top/t/topic/ial1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录