如何将MM/DD/YYYY格式时间字符串转为时间戳并解决strptime报错
问题原因与最优转换方案
核心错误原因
你使用的日期格式符月、日顺序与实际数据格式不匹配。你的数据是月/日/年的格式,你用了%d/%m/%Y(日/月/年)的解析规则,当遇到日期部分大于12的数值(如25、26)时,系统无法将其识别为合法月份,因此抛出值错误。
前3条数据运行未报错属于巧合:这三条的日期部分分别为12、5、12,均未超过12,系统误把日期值当成月份解析没有抛出异常,但实际解析得到的日期是完全错误的,比如2/12/2019会被解析为2019年12月2日,和实际的2019年2月12日不符。
最优转换方案
你使用的是pandas DataFrame结构,直接调用pd.to_datetime批量转换整列是效率最高的方案,无需逐行处理,也支持后续的时间、日期对比需求。
场景1:转换为完整UTC时间戳,与YYYY-MM-DD HH:MM:SS UTC格式对比
import pandas as pd import datetime # 批量转换整列为带UTC时区的datetime对象 temp_table_head['date_subscribed_dt'] = pd.to_datetime( temp_table_head['date_subscribed'], format='%m/%d/%Y %I:%M %p' # 显式指定格式,解析效率更高 ).dt.tz_localize('UTC') # 统一转为UTC时区,匹配对比格式要求 # 对比示例:筛选2019年3月25日0点UTC之后的订阅数据 target_dt = datetime.datetime(2019, 3, 25, tzinfo=datetime.timezone.utc) filter_result = temp_table_head[temp_table_head['date_subscribed_dt'] >= target_dt]
场景2:仅提取日期部分,与YYYY-MM-DD格式对比
无需拆分字符串,转换后直接提取日期部分即可:
# 批量提取日期列,格式为YYYY-MM-DD的date对象 temp_table_head['subscribe_date'] = pd.to_datetime( temp_table_head['date_subscribed'], format='%m/%d/%Y %I:%M %p' ).dt.date # 对比示例:筛选2019年3月25日及以后的订阅数据 target_date = datetime.date(2019, 3, 25) filter_result = temp_table_head[temp_table_head['subscribe_date'] >= target_date]
原有代码修正方案
如果你需要保留逐行处理的写法,仅需调换格式符中%m和%d的顺序即可:
第一种方案(转完整时间)修正后
example_date = temp_table_head['date_subscribed'][3] print(example_date) example_date=datetime.datetime.strptime(example_date, '%m/%d/%Y %I:%M %p') example_date
第二种方案(仅转日期)修正后
example_date = temp_table_head['date_subscribed'][3] print(example_date) example_date=example_date.split(' ')[0] print(example_date) example_date=datetime.datetime.strptime(example_date, '%m/%d/%Y') example_date
内容的提问来源于stack exchange,提问作者Nan Lin
相关产品推荐
相关产品推荐

