如何使用Python使CAST(日期时间)SQL Server函数



我有一个表达式CAST(0x0000A95A00B97B34 AS DateTime),它是2018-09-13 11:15:19.000。如何使用Python手动制作此CAST?我已经计算出dec格式的前8位是自2001年11月1日以来的天数,但时间不对。这是我的演职函数。

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

正如您所收集的,前两个字节是自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

最新更新