Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 928
SZA Avatar asked Nov 20 '15 19:11

SZA


People also ask

How do I extract only the date from a datetime object in Python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.

How do I get just the date in Python?

Use the datetime. date() Function to Convert Datetime to Date in Python. The datetime() constructor can be utilized to generate a date. The datetime() constructor has three parameters: day, month, and year.


1 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"]]
like image 62
julienc Avatar answered Oct 07 '22 16:10

julienc