从日期时间字符串中检索数据和时间

Retreive data and time from a datetime string

在我的项目中有这样一个字符串:

"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" 的值?

# 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

您需要准确匹配您的字符串。参考: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.

其中有一些空格和 : - 这与您的格式不符。