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?
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.
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.
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With