Use json module, to generate json text. Use the same Unix time for timestamp and formatted_time:
import json
import time
ts = int(time.time())
json_text = json.dumps(dict(
gpio="00000000",
timestamp=ts,
formatted_time=time.strftime("%A %b %d %X", time.localtime(ts)),
time_zone=read_tz_file(),
firmware="0.0"))
Note: in general, time.localtime(ts) may provide more info than datetime.now() e.g. in Python 2:
>>> import time
>>> from datetime import datetime
>>> ts = time.time()
>>> time.strftime('%Z%z')
'CEST+0200'
>>> time.strftime('%Z%z', time.localtime(ts))
'CEST+0000'
>>> datetime.now().strftime('%Z%z')
''
>>> datetime.fromtimestamp(ts).strftime('%Z%z')
''
Notice: only time.strftime('%Z%z') provides complete info for the local timezone on my machine, see python time.strftime %z is always zero instead of timezone offset.
On Python 3, datetime.now() too does not provide info about the local timezone:
>>> import time
>>> from datetime import datetime
>>> ts = time.time()
>>> time.strftime('%Z%z')
'CEST+0200'
>>> time.strftime('%Z%z', time.localtime(ts))
'CEST+0200'
>>> datetime.now().strftime('%Z%z')
''
>>> datetime.fromtimestamp(ts).strftime('%Z%z')
''
You could workaround it:
>>> from datetime import timezone
>>> datetime.now(timezone.utc).astimezone().strftime('%Z%z')
'CEST+0200'
>>> datetime.fromtimestamp(ts, timezone.utc).astimezone().strftime('%Z%z')
'CEST+0200'
If you want to work with datetime in Python 3; your code could look like:
#!/usr/bin/env python3
import json
from datetime import datetime, timedelta, timezone
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
local_time = datetime.now(timezone.utc).astimezone()
json_text = json.dumps(dict(
gpio="00000000",
timestamp=(local_time - epoch) // timedelta(seconds=1),
formatted_time=local_time.strftime("%A %b %d %X"),
time_zone=read_tz_file(),
firmware="0.0"))
**str(datetime.datetime.now().strftime("%A %b %d %X"))**to do? That's not legal Python syntax.