21

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?

Nathaniel Ford
  • 16,853
  • 18
  • 74
  • 88
SZA
  • 313
  • 1
  • 2
  • 5
  • 5
    As in `datetime.date()` and `datetime.time()`? – dhke Nov 20 '15 at 19:38
  • @dhke Sorry, duplicate comment. Internet is running slow here. I voted for your dupe target. – Two-Bit Alchemist Nov 20 '15 at 19:40
  • How do I apply datetime.date() and datetime.time() to the whole series – SZA Nov 20 '15 at 19:41
  • @Two-BitAlchemist No worries, conflict resolution is impossible in distributed systems without an arbiter ;-) – dhke Nov 20 '15 at 19:42
  • No, this question is not a duplicate for the question posted above. My question is different. I have dates in the form of timestamps. These dates are stored in a pandas dataframe. Using the code given above, I am adding a new column in the dataframe. This new column uses the fromtimestamp function of datetime to convert the time stamp to datetime. I now want to separate this datetime into date and time and save it into two new columns of the dataframe. – SZA Nov 20 '15 at 19:48
  • milestone['date'] = milestone['datetime'].map(pd.Timestamp.date) – Arun Kumar Khattri May 14 '18 at 14:31

1 Answers1

34

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"]]
julienc
  • 15,239
  • 15
  • 74
  • 77
  • I can do this. but I have datetime as a column in my DataFrame. I have to tokenize it into date and time. – SZA Nov 20 '15 at 19:42
  • This code works. Thanks :)>>> milestone["only_date"] = [d.date() for d in milestone["datetime"]] >>> milestone["only_time"] = [d.time() for d in milestone["datetime"]] – SZA Nov 20 '15 at 19:51