在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中,如果您将不包含时区信息的日期/时间字符串解析为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