python-3.x 将字符串转换为datetime对象和timestamp

cbeh67ev  于 2023-08-08  发布在  Python
关注(0)|答案(2)|浏览(103)

我已经将一个字符串转换为日期时间对象,从日期时间对象我得到了时间戳,当我将时间戳转换回日期时间时,我得到了不同的值。
string-->datetime format--> timestamp-->datetime

from datetime import datetime
import pandas as pd
import pytz

today = datetime.today().strftime('%Y:%m:%d')

col = ['HKH 13:30']
df = pd.DataFrame(col, columns=['snaptime'])
df['time_zone'] = df['snaptime'].str.split(' ', expand=True)[0]
df['time'] = df['snaptime'].str.split(' ', expand=True)[1]
df['timeobj'] = today + ' ' + df['time']
df['timeobj'] = df['timeobj'].apply(lambda x:datetime.strptime(x, '%Y:%m:%d %H:%M'))
hkhzone = pytz.timezone('Asia/Hong_Kong')
utc = pytz.timezone('UTC')
df['timeobj']  = df['timeobj'].apply(lambda x:hkhzone.localize(x))
df['UTC']  = df['timeobj'].apply(lambda x:x.replace(tzinfo=utc))
df['UTCTimestamp']  = df['UTC'].apply(lambda x:x.timestamp())
df['HKHtimestamp']  = df['timeobj'].apply(lambda x:x.timestamp())
df['UTCTime']  = df['UTCTimestamp'].apply(lambda x:datetime.fromtimestamp(x))
df['HKHtime']  = df['HKHtimestamp'].apply(lambda x:datetime.fromtimestamp(x))

字符串
输出:起始值为13:30,但最终得到11:00 x1c 0d1x

n9vozmp4

n9vozmp41#

实际上有几个问题。
1.当您替换timeobj中的时区时,实际上并没有将时间从Asia/Hong_Kong转换为UTC。
1.当您计算'UTCTimestamp'和'HKHtimestamp'时,它们实际上是相同的,因为两者都是从POSIX时间戳派生出来的,POSIX时间戳是时区不可知的(它是自1970-01-01 00:00:00 UTC以来的秒数)。
1.当您将'UTCTTimestamp'和'HKHtimestamp'转换回datetime时,Python会将这些时间戳视为运行脚本的机器的本地时区。
下面是一个让所有时区都知道并使用内置的ZoneInfo而不是pytz的示例。

from datetime import datetime, timezone
import pandas as pd
from zoneinfo import ZoneInfo

today = datetime.now(tz=timezone.utc).strftime('%Y-%m-%d')

col = ['HKH 13:30']
df = pd.DataFrame(col, columns=['snaptime'])
df['time_zone'] = df['snaptime'].str.split(' ', expand=True)[0]
df['time'] = df['snaptime'].str.split(' ', expand=True)[1]
df['timeobj'] = today + ' ' + df['time']
df['timeobj'] = df['timeobj'].apply(lambda x:datetime.strptime(x, '%Y-%m-%d %H:%M'))
hkhzone = ZoneInfo('Asia/Hong_Kong')
df['timeobj']  = df['timeobj'].apply(lambda x:x.replace(tzinfo=hkhzone))
df['UTCTimeObj']  = df['timeobj'].apply(lambda x:x.astimezone(ZoneInfo('UTC')))  
df['UTCTimestamp']  = df['UTCTimeObj'].apply(lambda x:x.timestamp())  
df['HKHtimestamp']  = df['timeobj'].apply(lambda x:x.timestamp())  
df['UTCTime']  = df['UTCTimestamp'].apply(lambda x:datetime.fromtimestamp(x, ZoneInfo('UTC')))  
df['HKHtime']  = df['HKHtimestamp'].apply(lambda x:datetime.fromtimestamp(x, hkhzone))  

display(df)

字符串
请注意以下几行

# This is now timezone aware
today = datetime.now(tz=timezone.utc).strftime('%Y-%m-%d')

hkhzone = ZoneInfo('Asia/Hong_Kong')

df['timeobj']  = df['timeobj'].apply(lambda x:x.replace(tzinfo=hkhzone))

# Convert time to UTC
df['UTCTimeObj']  = df['timeobj'].apply(lambda x:x.astimezone(ZoneInfo('UTC')))  

# Convert UTC timestamp to datetime in UTC
df['UTCTime']  = df['UTCTimestamp'].apply(lambda x:datetime.fromtimestamp(x, ZoneInfo('UTC')))  

# Convert HKH timestamp to datetime in HKH timezone
df['HKHtime']  = df['HKHtimestamp'].apply(lambda x:datetime.fromtimestamp(x, hkhzone))

mxg2im7a

mxg2im7a2#

您可以使用下面的代码来获得所需的输出

df['UTCTime']  = df['UTCTimestamp'].apply(lambda x:datetime.fromtimestamp(x, tz=pytz.UTC))

hkhzone = pytz.timezone('Asia/Hong_Kong')
df['HKHtime'] = df['HKHtimestamp'].apply(lambda x:datetime.fromtimestamp(x, tz=hkhzone))

字符串

相关问题