0

I want to convert the date in a column in a dataframe to a different format. Currently, it has this format: '2019-11-20T01:04:18'. I want it to have this format: 20-11-19 1:04.

I think I need to develop a loop and generate a new column for the new date format. So essentially, in the loop, I would refer to the initial column and then generate the variable for the new column in the format I want.

Can someone help me out to complete this task?

The following code works for one occasion:

import datetime
d = datetime.datetime.strptime('2019-11-20T01:04:18', '%Y-%m-%dT%H:%M:%S')
print d.strftime('%d-%m-%y %H:%M')
Vasilis
  • 143
  • 10

2 Answers2

1

From a previous answer in this site , this should be able to help you, comments give explanation You can read your data into pandas from csv or database or create some test data as shown below for testing.

>>> import pandas as pd
>>> df = pd.DataFrame({'column': {0: '26/1/2016', 1: '26/1/2016'}})
>>> # First convert the column to datetime datatype
>>> df['column'] = pd.to_datetime(df.column)
>>> # Then call the datetime object format() method, set the modifiers you want here
>>> df['column'] = df['column'].dt.strftime('%Y-%m-%dT%H:%M:%S') 

>>> df
                 column
0  2016-01-26T00:00:00
1  2016-01-26T00:00:00

NB. Check to ensure that all your columns have similar date strings

Gideon Maina
  • 849
  • 10
  • 25
  • Thank a lot, also how do I create a new column that says the week number? For example week 45, 46 etc. – Vasilis Nov 26 '19 at 10:07
  • You can do something like first change column to datetime `df['column'] = pd.to_datetime(df.column)` then call `>>> df['week'] = df['column'].dt.week` , this uses the dt.week value from the dt object – Gideon Maina Nov 26 '19 at 10:15
  • documentation at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.week.html – Gideon Maina Nov 26 '19 at 10:17
0

You can either achieve it like this:

from datetime import datetime

df['your_column'] = df['your_column'].apply(lambda x: datetime.strptime(x, '%Y-%m-%dT%H:%M:%S').strftime('%d-%m-%y %H:%M'))
Ayoub
  • 1,417
  • 14
  • 24
  • This is the error I get when I do that: "ValueError: unconverted data remains: +01:00" – Vasilis Nov 25 '19 at 14:24
  • your column contains some dates which doesn't have the format you mentioned, you have some date like this `'2019-11-20T01:04:18+01:00'` – Ayoub Nov 25 '19 at 14:30
  • I just noticed, so what do you advise on that? – Vasilis Nov 25 '19 at 14:35
  • you can either user `parse`function of `dateutil.parser`if you care about timezone offset, otherwise use slice `x[:19]` to convert the part that follow your format – Ayoub Nov 25 '19 at 14:49