Support more types to represent a date

This commit is contained in:
Lonami Exo 2017-12-28 12:32:16 +01:00
parent 75a342e24b
commit 3537e9bcc9
2 changed files with 20 additions and 6 deletions

View File

@ -1,4 +1,5 @@
from datetime import datetime
import struct
from datetime import datetime, date
from threading import Event
@ -125,6 +126,23 @@ class TLObject:
r.append(bytes(padding))
return b''.join(r)
@staticmethod
def serialize_datetime(dt):
if not dt:
return b'\0\0\0\0'
if isinstance(dt, datetime):
dt = int(dt.timestamp())
elif isinstance(dt, date):
dt = int(datetime(dt.year, dt.month, dt.day, dt).timestamp())
elif isinstance(dt, float):
dt = int(dt)
if isinstance(dt, int):
return struct.pack('<I', dt)
raise TypeError('Cannot interpret "{}" as a date.'.format(dt))
# These should be overrode
def to_dict(self, recursive=True):
return {}

View File

@ -540,11 +540,7 @@ class TLGenerator:
builder.write('TLObject.serialize_bytes({})'.format(name))
elif 'date' == arg.type: # Custom format
# 0 if datetime is None else int(datetime.timestamp())
builder.write(
r"b'\0\0\0\0' if {0} is None else "
r"struct.pack('<I', int({0}.timestamp()))".format(name)
)
builder.write('TLObject.serialize_datetime({})'.format(name))
else:
# Else it may be a custom type