Páginas

lunes, 24 de octubre de 2016

MS SQL DateTime a formato Wordpress XML


Hola!!

Esta vez el trabajo era pasar un dump de 1GB de 5 años de laburo en formato MS SQL a un Wordpress en MySQL.

Encaré el problema con Python para traducirlo al formato de importación XML del Wordpress. En este post les pongo específicamente el conversor de fechas.

MS SQL el formato DateTime lo regresa en el dump como un hexadesimal. Me ayudó esta respuesta que lo traduce a MySQL http://stackoverflow.com/questions/4946292/how-to-cast-the-hexadecimal-to-varchardatetime.

Les dejo el código!


# necesito convertir las fechas de formato CAST(0x0000A5F000472C53 AS DateTime) = Viernes, 22 de Abril de 2016
import datetime
import re

# http://stackoverflow.com/questions/4946292/how-to-cast-the-hexadecimal-to-varchardatetime
# SELECT 
      # CAST(
          # '1900-01-01 00:00:00' + 
          # INTERVAL CAST(CONV(substr(HEX(BinaryData),1,8), 16, 10)  AS SIGNED) DAY +
          # INTERVAL CAST(CONV(substr(HEX(BinaryData),9,8), 16, 10)  AS SIGNED)* 10000/3 MICROSECOND
      # AS DATETIME) AS converted_datetime
# FROM
# (
# SELECT 0x0000987C00000000 AS BinaryData
# UNION ALL
# SELECT 0x00009E85013711EE AS BinaryData
# ) d

def getFiletime(dt):
    # CAST(0x0000A5F000472C53 AS DateTime)
    # print dt.group(0)
    temphex = dt.group(0)
    # print 'temphex:' + temphex
    tempsub18 = temphex[7:15]
    # print 'tempsub18:' + tempsub18
    tempsub916 = temphex[15:23]
    # print 'tempsub916:' + tempsub916
    dias = int(tempsub18, 16)
    microsegundos = int(tempsub916, 16) * 10000/3
    return format(datetime.datetime(1900, 1, 1) + datetime.timedelta(dias, 0, microsegundos), '%a, %d %B %Y %H:%M:%S %Z')
    
    
fname = raw_input("Ingresa nombre de archivo: ")
if len(fname) < 1 : fname = "contenido-demo.sql"

fh = open(fname)
f = open('contenido-fechasbien.sql','w+')
 
for linea in fh:
    if linea.find("CAST(0x") != -1: 
        
        linea = re.sub('CAST\(0x([^\s]+) AS DateTime\)', getFiletime, linea)        
        f.write(linea)
    else:
        #guardar la linea en la tabla creada antes
        f.write(linea)

No hay comentarios.: