只获取时间数据过时和时间字符串.

Nil*_*age 2 python time

我想只获取这种日期格式的时间数据?在下面的例子中是23:55:00.我试过很多方法,包括datetime.strptime,from dateutil import parser等,但失败了.:(如何用Python做到这一点?

[15/Apr/2013:23:55:00 +0530]
Run Code Online (Sandbox Code Playgroud)

Syl*_*oux 6

假设您可以将"日期"作为字符串访问:

>>> from datetime import datetime

>>> time_string = "[15/Apr/2013:23:55:00 +0530]"

>>> format = "[%d/%b/%Y:%H:%M:%S %z]"
>>> dt = datetime.strptime(time_string, format)
>>> dt
datetime.datetime(2013, 4, 15, 23, 55, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))

# 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'
Run Code Online (Sandbox Code Playgroud)

如果你肯定绝对肯定日期有固定的格式,你可以只切片你的字符串:

>>> time_string = "[15/Apr/2013:23:55:00 +0530]"
>>> time_string[-15:-7]
'23:55:00'
Run Code Online (Sandbox Code Playgroud)

这只是一个例子.Python有很多字符串操作函数可能更适合您的数据.不要犹豫,看看他们!