如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
如何将以下字符串转换为datetime对象?
"Jun 1 2005 1:33PM"
当前回答
这里没有提到但很有用的一点:在当天添加后缀。我解耦了后缀逻辑,这样你就可以将它用于任何你喜欢的数字,而不仅仅是日期。
import time
def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy
tens = int(str(n)[-2:])
units = n % 10
if tens > 10 and tens < 20:
return suf[0] # teens with 'th'
elif units <= 3:
return suf[units]
else:
return suf[0] # 'th'
def day_suffix(t):
'''
Returns the suffix of the given struct_time day
'''
return num_suffix(t.tm_mday)
# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))
其他回答
datetime.strptime将用户指定格式的输入字符串解析为时区原始日期时间对象:
>>> from datetime import datetime
>>> datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime.datetime(2005, 6, 1, 13, 33)
要使用现有的datetime对象获取日期对象,请使用.date()对其进行转换:
>>> datetime.strptime('Jun 1 2005', '%b %d %Y').date()
date(2005, 6, 1)
链接:
strptime文档:Python 2、Python 3strptime/strftime格式字符串文档:Python 2,Python 3strftime.org格式字符串备忘单
笔记:
strptime=“字符串解析时间”strftime=“字符串格式时间”
与Javed的回答类似,我只是想要字符串中的日期-所以结合Simon和Javed逻辑,我们得到:
from dateutil import parser
import datetime
s = '2021-03-04'
parser.parse(s).date()
输出
日期时间日期(2021 3月4日)
看看我的答案。
在真实数据中,这是一个真正的问题:多个、不匹配、不完整、不一致和多语言/地区日期格式,通常在一个数据集中自由混合。生产代码失败是不好的,更不用说像狐狸一样高兴异常了。
我们需要尝试。。。捕获多个日期时间格式fmt1,fmt2,。。。,fmtn和抑制/处理所有不匹配的异常(来自strptime())(特别是,避免需要try…catch子句的yukky-n-deep缩进阶梯)。从我的解决方案
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
记住这一点,您不需要再次在日期时间转换中感到困惑。
日期时间对象字符串=strptime
datetime对象转换为其他格式=strftime
2005年6月1日下午1:33
等于
%b%d%Y%I:%M%p
%b月作为区域设置的缩写名称(Jun)%d月份的日期,以零填充的小数(1)表示%Y年,以世纪为小数(2015年)%I小时(12小时时钟)为零填充小数(01)%M分钟作为零填充十进制数字(33)%p Locale相当于AM或PM(PM)
所以您需要strptime i-e将字符串转换为
>>> dates = []
>>> dates.append('Jun 1 2005 1:33PM')
>>> dates.append('Aug 28 1999 12:00AM')
>>> from datetime import datetime
>>> for d in dates:
... date = datetime.strptime(d, '%b %d %Y %I:%M%p')
... print type(date)
... print date
...
输出
<type 'datetime.datetime'>
2005-06-01 13:33:00
<type 'datetime.datetime'>
1999-08-28 00:00:00
如果您有不同的日期格式,您可以使用panda或dateutil.parse
>>> import dateutil
>>> dates = []
>>> dates.append('12 1 2017')
>>> dates.append('1 1 2017')
>>> dates.append('1 12 2017')
>>> dates.append('June 1 2017 1:30:00AM')
>>> [parser.parse(x) for x in dates]
输出
[datetime.datetime(2017, 12, 1, 0, 0), datetime.datetime(2017, 1, 1, 0, 0), datetime.datetime(2017, 1, 12, 0, 0), datetime.datetime(2017, 6, 1, 1, 30)]
Use:
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")
emp.info()
它显示“开始日期时间”列和“上次登录时间”都是数据帧中的“对象=字符串”:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name 933 non-null object
Gender 855 non-null object
Start Date 1000 non-null object
Last Login Time 1000 non-null object
Salary 1000 non-null int64
Bonus % 1000 non-null float64
Senior Management 933 non-null object
Team 957 non-null object
dtypes: float64(1), int64(1), object(6)
memory usage: 62.6+ KB
通过使用read_csv中的parse_dates选项,可以将字符串datetime转换为panda datetime格式。
emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv", parse_dates=["Start Date", "Last Login Time"])
emp.info()
输出:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 8 columns):
First Name 933 non-null object
Gender 855 non-null object
Start Date 1000 non-null datetime64[ns]
Last Login Time 1000 non-null datetime64[ns]
Salary 1000 non-null int64
Bonus % 1000 non-null float64
Senior Management 933 non-null object
Team 957 non-null object
dtypes: datetime64[ns](2), float64(1), int64(1), object(4)
memory usage: 62.6+ KB