Skip to content

Commit

Permalink
Support more types to represent a date
Browse files Browse the repository at this point in the history
  • Loading branch information
Lonami committed Dec 28, 2017
1 parent 75a342e commit 3537e9b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
20 changes: 19 additions & 1 deletion telethon/tl/tlobject.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
import struct
from datetime import datetime, date
from threading import Event


Expand Down Expand Up @@ -125,6 +126,23 @@ def serialize_bytes(data):
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 {}
Expand Down
6 changes: 1 addition & 5 deletions telethon_generator/tl_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,11 +540,7 @@ def write_to_bytes(builder, arg, args, name=None):
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
Expand Down

0 comments on commit 3537e9b

Please sign in to comment.