Python和MATLAB在从日期时间计算POSIX方面的分歧

问题描述 投票:1回答:1

在MATLAB中,我可以轻松地将datetime对象转换为posix:

start_time = datetime('2020-04-30 10:05:00');
start_time_unix = posixtime(start_time)

返回:

start_time_unix = 1.588241100000000e+09.

在Python中,我创建了一个类似的datetime对象,并尝试将其转换为posix:

import time
import datetime
import numpy as np

time_string = '2020-04-30 10:05:00'
calendar, clock = time_string.split(' ')
year,month,day = [np.int(x) for x in calendar.split('-')]
hour,minute,second = [np.int(x) for x in clock.split(':')]
dt = datetime.datetime(year, month, day, hour, minute, second)
ut = time.mktime(dt.timetuple())

在那一点上,

ut = 1588262700.0

如果小时和分钟混合在一起,则

dt2 = datetime.datetime(year, month, day, minute, hour, second)
ut2 = time.mktime(dt2.timetuple())

返回

ut2 = 1588245000.0

为什么我会看到MATLAB和Python之间存在这种差异?另外,有没有一种方法可以解析日期/时间字符串并将其更有效地转换为posix?

python-3.x matlab datetime posix
1个回答
0
投票

[在Python中,如果您将不包含时区信息的日期/时间字符串解析为datetime对象,则结果对象是天真的,即它不知道任何时区。 Python默认情况下将假定对象属于您的操作系统的时区!

对于给定的示例,您将需要指定时区信息以避免产生歧义:

from datetime import datetime, timezone

# parse to datetime, in this case we don't need strptime since string is ISO8601 compatible
dtobj = datetime.fromisoformat('2020-04-30 10:05:00')
# naive, no tz info: datetime.datetime(2020, 4, 30, 10, 5)

# add a timezone, for UTC, we can use timezone.utc from the datetime module:
dtobj = dtobj.replace(tzinfo=timezone.utc)
# tz-aware: datetime.datetime(2020, 4, 30, 10, 5, tzinfo=datetime.timezone.utc)

# now we can obtain the posix timestamp:
posix = dtobj.timestamp()

print(posix)
# 1588241100.0
© www.soinside.com 2019 - 2024. All rights reserved.