你如何只从 python 日期时间中提取日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33834727/
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
How do you extract only the date from a python datetime?
提问by SZA
I have a dataframe in python. One of its columns is labelled time
, which is a timestamp. Using the following code, I have converted the timestamp to datetime
:
我在 python 中有一个数据框。其中一列标记为time
,这是一个时间戳。使用以下代码,我已将时间戳转换为datetime
:
milestone['datetime'] = milestone.apply(lambda x: datetime.datetime.fromtimestamp(x['time']), axis = 1)
Now I want to separate (tokenize) date and time and have two different columns like milestone['only_date']
and milestone['only_time']
. How do I do this?
现在我想分离(标记)日期和时间,并有两个不同的列,如milestone['only_date']
和milestone['only_time']
。我该怎么做呢?
采纳答案by julienc
You can use date
and time
methods of the datetime
class to do so:
您可以使用类的date
和time
方法datetime
来做到这一点:
>>> from datetime import datetime
>>> d = datetime.now()
>>> only_date, only_time = d.date(), d.time()
>>> only_date
datetime.date(2015, 11, 20)
>>> only_time
datetime.time(20, 39, 13, 105773)
Hereis the datetime
documentation.
这是datetime
文档。
Applied to your example, it can give something like this:
应用于您的示例,它可以给出如下内容:
>>> milestone["only_date"] = [d.date() for d in milestone["datetime"]]
>>> milestone["only_time"] = [d.time() for d in milestone["datetime"]]