python中的日期时间分割
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33810980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date Time split in python
提问by Saravana Murthy
I have to split a date time which I get from a software in the below format to separate variables (year,month,day,hour, min,sec)
我必须分割我从以下格式的软件中获得的日期时间以分隔变量(年、月、日、小时、分钟、秒)
19 Nov 2015 18:45:00.000
Note : There is two spaces between the date and time. The whole date and time is stored in a single string variable. Please help me in this regards.
注意:日期和时间之间有两个空格。整个日期和时间存储在单个字符串变量中。请在这方面帮助我。
Thanks in advance.
提前致谢。
采纳答案by Cedric Zoppolo
Below solution should work for you:
以下解决方案应该适合您:
import datetime
string = "19 Nov 2015 18:45:00.000"
date = datetime.datetime.strptime(string, "%d %b %Y %H:%M:%S.%f")
print date
Output would be:
输出将是:
2015-11-19 18:45:00
And you can access the desired values with:
您可以通过以下方式访问所需的值:
>>> date.year
2015
>>> date.month
11
>>> date.day
19
>>> date.hour
18
>>> date.minute
45
>>> date.second
0
You can check datetime's package documentationunder section 8.1.7 for srtptime
function's usage.
回答by Kendas
Use datetime.strptime(your_string, format)
用 datetime.strptime(your_string, format)
To contsruct the format
string, consult the documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
要构造format
字符串,请参阅文档:https: //docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
From there, you can easily get the year, month, etc.(also in the documentation)
从那里,您可以轻松获取年、月等(也在文档中)
回答by wim
First pip install python-dateutil
then do:
首先pip install python-dateutil
然后做:
>>> from dateutil.parser import parse
>>> dt = parse('19 Nov 2015 18:45:00.000')
>>> dt.year
2015
>>> dt.month
11
>>> dt.day
19
>>> dt.hour
18
>>> dt.minute
45
>>> dt.second
0
回答by Andy
As an alternative to wim's answer, if you don't want to install a package, you can do it like so:
作为 wim 的答案的替代方法,如果您不想安装软件包,可以这样做:
import datetime
s = "19 Nov 2015 18:45:00.000"
d = datetime.datetime.strptime(s, "%d %b %Y %H:%M:%S.%f")
print d.year
print d.month
print d.day
print d.hour
print d.minute
print d.second
This outputs:
这输出:
2015
11
19
18
45
0
This utilizes strptime
to parse the string.
这strptime
用于解析字符串。