在我的项目中,我有一个像这样的字符串:
" 2018-03-07 06:46:02.737951"
我想得到两个变量:一个是日期格式,包含数据,另一个是时间。
我试过了:
from datetime import datetime
datetime_object = datetime.strptime('2018-03-07 06:46:02.737951', '%b %d %Y %I:%M%p')
但是我收到了错误。
然后我尝试了:
from dateutil import parser
dt = parser.parse("2018-03-07 06:46:02.737951")
但我不知道如何处理这些结果。
如何提取我的变量的值" date_var"和" time_var"?
答案 0 :(得分:3)
# Accessing the time as an object:
the_time = dt.time()
#the_time
datetime.time(23, 55)
# Accessing the time as a string:
the_time.strftime("%H:%M:%S")
'23:55:00'
类似于日期
参考here
答案 1 :(得分:3)
您需要完全匹配您的字符串。参考:strftime-and-strptime-behavior
from datetime import datetime
dt = datetime.strptime('2018-03-07 06:46:02.737951', '%Y-%m-%d %H:%M:%S.%f')
print(dt.date())
print(dt.time())
d = dt.date() # extract date
t = dt.time() # extract time
print(type(d)) # printout the types
print(type(t))
输出:
2018-03-07
06:46:02.737951
<class 'datetime.date'>
<class 'datetime.time'>
您的格式字符串类似于:
Month as locale’s abbreviated name.
Day of the month as a zero-padded decimal number.
Year with century as a decimal number.
Hour (12-hour clock) as a zero-padded decimal number.
Minute as a zero-padded decimal number.
Locale’s equivalent of either AM or PM.
其中包含一些空格和:
- 与您的格式不符。