简体   繁体   English

如何使用 Pandas 在 Python 中格式化日期和时间

[英]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:我需要一种方法将2021-01-27T12:00:17Z中的日期和时间重新格式化为单独的日期和时间变量,格式如下所示:

Date : 27/01/2021日期: 27/01/2021
Time : 12:00时间: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.当我将语法从format='%Y-%m-%dT%H:%M:%SZ'更改为format='%d-%m-%YT%H:%M:%SZ'时,它会产生一个错误。

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.日期和时间是 datetime.datetime 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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