import pandas as pd
dates = ['2015-12-25', '2015-12-26']
# 1) Use a list comprehension.>>> [d.date() for d in pd.to_datetime(dates)][datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
# 2) Convert the dates to a DatetimeIndex and extract the python dates.>>> pd.DatetimeIndex(dates).date.tolist()[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
计时
dates = pd.DatetimeIndex(start='2000-1-1', end='2010-1-1', freq='d').date.tolist()
>>> %timeit [d.date() for d in pd.to_datetime(dates)]# 100 loops, best of 3: 3.11 ms per loop
>>> %timeit pd.DatetimeIndex(dates).date.tolist()# 100 loops, best of 3: 6.85 ms per loop
def try_strptime(s, fmts=['%d-%b-%y','%m/%d/%Y']):for fmt in fmts:try:return datetime.strptime(s, fmt)except:continue
return None # or reraise the ValueError if no format matched, if you prefer
from dateutil.parser import parse
# Function that'll guess the format and convert it into the python datetime formatdef update_event(start_datetime=None, end_datetime=None, description=None):if start_datetime is not None:new_start_time = parse(start_datetime)
return new_start_time
# Sample input dates in different formatsd = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']
new = [update_event(i) for i in d]
for date in new:print(date)# Sample output dates in Python datetime object# 2014-04-23 00:00:00# 2013-04-24 00:00:00# 2014-04-25 00:00:00
from dateutil.parser import parse
def update_event(start_datetime=None, end_datetime=None, description=None):if start_datetime is not None:new_start_time = parse(start_datetime)
return new_start_time
# Sample input dates in different formatsd = ['06/07/2021 06:40:23.277000', '06/07/2021 06:40', '06/07/2021']
# Passing the dates one by one through the functionnew = [update_event(i) for i in d]
for date in new:print(date.strftime('%Y/%m/%d %H:%M:%S.%f'))# Sample output dates in required Python datetime object# 2021/06/07 06:40:23.277000# 2021/06/07 06:40:00.000000# 2021/06/07 00:00:00.000000