简体   繁体   中英

How To Format Date and Time in Python Using Pandas

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.

I am using these, hope it helps;

from datetime import datetime, timedelta, timezone

utc_time = datetime.fromtimestamp(date_time).astimezone(timezone.utc)
local_time = datetime.fromtimestamp(date_time).astimezone(local_tz)

date = datetime.fromisoformat(date_time).astimezone(local_tz).date
time = datetime.fromisoformat(date_time).astimezone(local_tz).time

for datetime calculation, we can use timedelta
local_time = datetime.fromtimestamp(date_time).astimezone(local_tz) + deltatime(hours=5)
local_time = datetime.fromtimestamp(date_time).astimezone(local_tz) + deltatime(minutes=60)


<built-in method date of datetime.datetime object at 0x000002BF40795DA0>
<built-in method time of datetime.datetime object at 0x000002BF40795DA0>

the date and time are datetime.datetime objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM