def insert_datetime(self):
d = datetime.today()
# d是日期时间对象,带微秒部分
print(d) # 2022-04-08 09:10:46.181748
print('d type:', type(d)) # d type: <class 'datetime.datetime'>
# 将d转换为日期时间格式字符串,如果不指定参数,得到的字符串是带微秒部分的
# 带微秒部分的字符串写入MSSQL时会报错,字符串转日期时间格式失败。
# 所以需要指定参数 timespec="seconds" 指定转换出的字符串的时间部分保留到秒级,默认是"auto",或不指定,则保留到微秒级
# sep=' ' 是指定转换出的字符串中,日期部分与时间部分之间的分隔符,默认是T,
datetime_now = d.isoformat()
print(datetime_now) # 2022-04-08T08:50:30.050189
today_now = d.isoformat(sep=' ', timespec="seconds")
print(today_now) # 2022-04-08 08:50:30
print('today_now type:', type(today_now)) # today_now type: <class 'str'>
# 此时插入MSSQL,就只需要在参数位上添加引号,不用做其他类型转换,MSSQL会自动将该字符串转为日期时间格式写入表中 前提是表字段类型是datetime
# in_sql = """insert into test_date (test_date) values(convert(datetime, '{}', 20))""".format(today_now)
in_sql = """insert into test_date (test_date) values('{}')""".format(today_now)
print(in_sql)
self.cur_his_utf.execute(in_sql)
self.conn_his_utf.commit()
# 以上是根据日期时间对象得到日期时间字符串,如果要自定义日期时间
# 首先需要得到年, 月, 日, 时, 分, 秒的整数形式,然后用datetime()函数将其构造为日期时间对象
# 得到的日期时间对象,因为只包含秒级,所以可直接用于MSSQL写入
year = 2022
month = 4
day = 8
hour = 8
minute = 56
second = 20
datetime_obj = datetime(year, month, day, hour, minute, second)
print('datetime_obj type:', type(datetime_obj)) # datetime_obj type: <class 'datetime.datetime'>
print(datetime_obj) # 2022-04-08 08:56:20
in_sql = """insert into test_date (test_date) values('{}')""".format(datetime_obj)
self.cur_his_utf.execute(in_sql)
self.conn_his_utf.commit()
# 如果只想获取到yyyy-mm-dd形式的日期对象,则使用date()函数构造,入参为年, 月, 日
# 获取到的日期对象也可直接写入MSSQL 如果MSSQL对应字段类型是datetime,则MSSQL自动以0填充时,分,秒部分
date_obj = date(year, month, day)
print('date_obj type:', type(date_obj)) # <class 'datetime.date'>
print(date_obj) # 2022-04-08
in_sql = """insert into test_date (test_date) values('{}')""".format(date_obj)
self.cur_his_utf.execute(in_sql)
self.conn_his_utf.commit()
Python pymssql 向MSSQL数据库写入日期时间
最新推荐文章于 2023-07-06 15:13:46 发布