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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:01:03  来源:igfitidea点击:

Date Time split in python

pythonpython-2.7

提问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 srtptimefunction's usage.

您可以在第 8.1.7 节下查看datetime 的包文档了解srtptime函数的用法

回答by Kendas

Use datetime.strptime(your_string, format)

datetime.strptime(your_string, format)

To contsruct the formatstring, 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-dateutilthen 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 strptimeto parse the string.

strptime用于解析字符串。