dev:index
Developers
Questa pagina è il magazzino per le informazioni degli sviluppatori.
Ora qui appunto sul tempo e python...
Parliamo della conversione tra Unix Timestamp e Date time con Timezone, in Django e in SQL.
Output di un codice di test nella piattaforma my-iot-framework
:
--- Testing timestamps datetime conversions.. UNIX TIMESTAMP ts = 1 --- [UNAWARE] fromtimestamp = dtunaware = datetime.datetime(1970, 1, 1, 1, 0, 1) [UNAWARE] dtunaware.strftime("%s") = '1' [UNAWARE] defaultfilters.date(dtunaware, "U") = '1' [UNAWARE] EXTRACT EPOCH dtunaware_metrics[0]["ts"] = 3601 --- [AWARE] fromtimestamp.replace(tzinfo=UTC): dtaware = datetime.datetime(1970, 1, 1, 1, 0, 1, tzinfo=<UTC>) [AWARE] dtaware.strftime("%s") = '1' [AWARE] defaultfilters.date(dtaware, "U") = '3601' [AWARE] EXTRACT EPOCH dtaware_metrics[0]["ts"] = 7201 --- [UTC] utcfromtimestamp: utcdt = datetime.datetime(1970, 1, 1, 0, 0, 1) [UTC] utcdt.strftime("%s") = '-3599' [UTC] defaultfilters.date(utcdt, "U") = '-3599' [UTC] EXTRACT EPOCH utcdt_metrics[0]["ts"] = 1
Codice per riprodurre questo output nella shell Django manage.py shell
:
from datetime import datetime import pytz from django.template import defaultfilters from django.db.models.functions import Extract from web.models import Board from web.models.metrics import get_board_metric_model ts = 1 dtunaware = datetime.fromtimestamp(ts) dtaware = datetime.fromtimestamp(ts).replace(tzinfo=pytz.UTC) utcdt = datetime.utcfromtimestamp(ts) board = Board.objects.first() m = get_board_metric_model(board) m.objects.create(time=utcdt, data={}) m.objects.create(time=dtaware, data={}) m.objects.create(time=dtunaware, data={}) dtunaware_metrics = m.objects.filter(time=dtunaware).annotate(ts=Extract("time", "epoch")).values() dtaware_metrics = m.objects.filter(time=dtaware).annotate(ts=Extract("time", "epoch")).values() utcdt_metrics = m.objects.filter(time=utcdt).annotate(ts=Extract("time", "epoch")).values() print("---") print(f"Testing timestamps datetime conversions..") print(f"UNIX TIMESTAMP {ts = }") print("---") print(f"[UNAWARE] fromtimestamp = {dtunaware = }") print(f'[UNAWARE] {dtunaware.strftime("%s") = }') print(f'[UNAWARE] {defaultfilters.date(dtunaware, "U") = }') print(f'[UNAWARE] EXTRACT EPOCH {dtunaware_metrics[0]["ts"] = }') print("---") print(f"[AWARE] fromtimestamp.replace(tzinfo=UTC): {dtaware = }") print(f'[AWARE] {dtaware.strftime("%s") = }') print(f'[AWARE] {defaultfilters.date(dtaware, "U") = }') print(f'[AWARE] EXTRACT EPOCH {dtaware_metrics[0]["ts"] = }') print("---") print(f"[UTC] utcfromtimestamp: {utcdt = }") print(f'[UTC] {utcdt.strftime("%s") = }') print(f'[UTC] {defaultfilters.date(utcdt, "U") = }') print(f'[UTC] EXTRACT EPOCH {utcdt_metrics[0]["ts"] = }')
Benedette siano le f-strings per il debug!
dev/index.txt · Last modified: 2021/09/02 14:38 by feroda