【问题标题】:Retreive data and time from a datetime string从日期时间字符串中检索数据和时间
【发布时间】:2018-03-12 15:45:54
【问题描述】:

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

“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”的值?

【问题讨论】:

标签: python date datetime date-parsing


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    # 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2018-02-19
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多