你如何只从 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

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

How do you extract only the date from a python datetime?

pythondatetimepandastokenize

提问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 dateand timemethods of the datetimeclass to do so:

您可以使用类的datetime方法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 datetimedocumentation.

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"]]