Python 代码:将日期字符串转换为时间戳 (支持多种格式)
你可以使用datetime模块来实现日期格式的转换和时间戳的获取。下面是一个示例代码:\n\npython\nfrom datetime import datetime\n\ndef convert_to_timestamp(date_string):\n formats = ["%Y-%m-%d", "%Y年%m月%d日", "%Y年%m月"]\n \n for date_format in formats:\n try:\n date = datetime.strptime(date_string, date_format)\n timestamp = datetime.timestamp(date)\n return int(timestamp)\n except ValueError:\n pass\n \n return None\n\n# 测试示例\n date_str1 = "2022-01-01"\n timestamp1 = convert_to_timestamp(date_str1)\n print(f"{date_str1}的时间戳为:{timestamp1}")\n\n date_str2 = "2022年01月01日"\n timestamp2 = convert_to_timestamp(date_str2)\n print(f"{date_str2}的时间戳为:{timestamp2}")\n\n date_str3 = "2022年01月"\n timestamp3 = convert_to_timestamp(date_str3)\n print(f"{date_str3}的时间戳为:{timestamp3}")\n\n\n输出结果:\n\n\n2022-01-01的时间戳为:1640995200\n2022年01月01日的时间戳为:1640995200\n2022年01月的时间戳为:1640995200\n\n\n注意,如果日期格式不符合所列的三种格式,函数将返回None。
原文地址: https://www.cveoy.top/t/topic/p4xP 著作权归作者所有。请勿转载和采集!