-1

My Python field values look like below:

Metrics_Values
2017-12-31 00:00:00
UW Value
2017-12-31 00:00:00
2017-12-31 00:00:00

I want below output:

Metric_Values
12/31/2017
UW Value
12/31/2017
12/31/2017

I tried several different manipulations on this dataframe but as the values are in object datatype and as I have some text values too, I'm having trouble to get what I need.

Appreciate any pointers. Thank you

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
ysl
  • 51
  • 6

2 Answers2

1

I would not recommend using multiple types of data within the same serie but here is a code that would do the work for you:

df.Metrics_Values = df.Metrics_Values.map(lambda x: x.date() if isinstance(x, datetime.datetime) else x)
Alex
  • 816
  • 5
  • 14
0

You can use strptime (which converts a string to a datetime object) and strftime (which converts a datetime object to a string) from datetime to format your dates as you wish. Here's an example:

import datetime as dt

def convert_format(date_string):
    return dt.datetime.strptime(date_string,'%Y-%m-%d %H:%M:%S').strftime('%Y/%m/%d')

Then apply this method to your dataframe or series:

df.time_column.apply(lambda x: convert_format(x))

For the input:

0  2017-12-31 00:00:00
1  2017-12-31 00:00:00

using the above code results in:

0    2017/12/31
1    2017/12/31

See the docs on strptime and strftime for more on how they work: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
  • Thanks for your reply Henry. But this solution doesn't work for me as I've few text valued rows along with datetime rows. – ysl Aug 30 '18 at 19:35
  • @ysl in that case I'd recommend splitting up this column into separate columns or separate DataFrames. DataFrame columns should be only of one type (as Alex mentioned) – Henry Woody Aug 30 '18 at 19:47
  • If you really must keep this format (not recommended), then you could add a line to the code I've posted where you check if the value is a date or not first. Here's how you can check if a string is in a datetime format: https://stackoverflow.com/questions/25341945/check-if-string-has-date-any-format . Then in this code, change `df.time_column.apply(lambda x: convert_format(x))` to `df.time_column.apply(lambda x: convert_format(x) if is_date(x) else x)` – Henry Woody Aug 30 '18 at 19:52