如何使用Python实现强制转换(datetime)SQL Server函数

2024-06-17 15:10:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表达式CAST(0x0000A95A00B97B34 AS DateTime),它是2018-09-13 11:15:19.000。如何使用Python手动进行此转换?我已经计算出dec格式的前8位数字是自1900年1月1日起的天数,但时间是错误的。这是我的cast函数

def castDateTime(hexVal):
    hexDate = hexVal[2:10]
    hexTime = hexVal[10:]
    intDate = int(hexDate, 16)
    intTime = int(hexTime, 16)
    Date = datetime.strptime("00:00:00", "%H:%M:%S") + timedelta(days=intDate) + timedelta(milliseconds=intTime)
    return Date

print castDateTime('0x0000A95A00B97B34')

重新运行:2018-09-13 03:22:35.700000 实际值2018-09-13 11:15:19.000


Tags: datetimedate表达式as手动dectimedeltaint
1条回答
网友
1楼 · 发布于 2024-06-17 15:10:13

正如您所收集的,前两个字节是自1900年1月1日以来的天数;最后2个字节是从午夜开始的滴答声数,其中1滴答声等于1/300秒

因此,以下各项应产生正确的结果:

def castDateTime(hexVal):
    hexDate = hexVal[2:10]
    hexTime = hexVal[10:]
    intDate = int(hexDate, 16)
    intTime = int(hexTime, 16) / 300
    Date = datetime.strptime("00:00:00", "%H:%M:%S") + timedelta(days=intDate) + timedelta(seconds=intTime)
    return Date

相关问题 更多 >