0

I want serialize datetime with json but before serialization I need to convert local time into utc time how can I do it if I know tzinfo?

import datetime

def some_conversion(d):
  ???

# assume that now() and utcnow() is taken in same time - this code is not valid to test it.
assert(some_conversion(datetime.datetime.now()) == datetime.datetime.utcnow())

I prepare some serialization function but has not idea how to solve conversion. I want to serialize datetime in utc format with very high speed and full precision.

import datetime
import json
import timeit

d = datetime.datetime.utcnow()

def date_tuple():
  x = (d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond)
  y = json.dumps(x)
  z = json.loads(y)
  b = datetime.datetime(*z)

print timeit.timeit(date_tuple, number=1000)

if d != b: raise ValueError(d-b)

ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48
Chameleon
  • 9,722
  • 16
  • 65
  • 127

1 Answers1

0

Have you tried pytz module?

Assume you have Vladivostok time zone.

import pytz, datetime
local = pytz.timezone("Asia/Vladivostok")
naive_dt = datetime.datetime.now()
local_dt = local.localize(naive_dt, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)

Also check this question

valignatev
  • 6,020
  • 8
  • 37
  • 61