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

Question:

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:

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?

Asked By: SZA

||

Answers:

You can use date and time methods of the datetime class to do so:

>>> 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)

Here is the datetime documentation.

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"]]
Answered By: julienc
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.