Home > other >  How To Format Date and Time in Python Using Pandas
How To Format Date and Time in Python Using Pandas

Time:01-27

I need a way to reformat the date and time from 2021-01-27T12:00:17Z as a separate date and time variable in the format as shown below:

Date: 27/01/2021
Time: 12:00

import pandas as pd

values = {'dates':  ['2021-01-27T12:00:17Z']}

df = pd.DataFrame(values)
df['dates'] = pd.to_datetime(df['dates'], format='%Y-%m-%dT%H:%M:%SZ')


formatted_date = pd.to_datetime(df['dates']).dt.date
print('Formatted Date:',formatted_date)
formatted_time = pd.to_datetime(df['dates']).dt.time
print('Formatted Time:',formatted_time)

print ('df value:', df)
print (df.dtypes)    

When I change the syntax from format='%Y-%m-%dT%H:%M:%SZ' to format='%d-%m-%YT%H:%M:%SZ' it produces an error.

Any help would be much appreciated.

CodePudding user response:

You can use:

print(df["dates"].apply(lambda x: x.strftime("%d/%m/%Y")))
0    27/01/2021

and

print(df["dates"].apply(lambda x: x.strftime("%d-%m-%Y")))
0    12:00

PS: but note, if you overwrite the columns into these formats, they will become strings. Just use it for printing purposes, but don't change the format of the datetime column.

CodePudding user response:

I am using these, hope it helps;

utc_time = datetime.fromtimestamp(date_time).astimezone(timezone.utc)
local_time = datetime.fromtimestamp(date_time).astimezone(local_tz)
date_time1 = datetime.fromisoformat(date_time).astimezone(local_tz).date
date_time2 = datetime.fromisoformat(date_time).astimezone(utc_time).time

date = date_time1.date
time = date_time1.time
  •  Tags:  
  • Related