Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Last active June 28, 2022 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivanleoncz/dea83f687c75cf2333702f81baecf569 to your computer and use it in GitHub Desktop.
Save ivanleoncz/dea83f687c75cf2333702f81baecf569 to your computer and use it in GitHub Desktop.
Time Operations in Python
import os
import time
print("Operating System: ", os.uname().sysname)
print("\nTime in UTC since Unix time epoch (1970-01-01 00:00:00).")
print("As seconds: ", time.time())
print("As string: ", time.ctime())
print("Seconds in the future: ", time.ctime(2065944467))
print("One second behind epoch: ", time.ctime(-1))
# $ python3 ex_1.py
# Operating System: Linux
#
# Time in UTC since Unix time epoch (1970-01-01 00:00:00).
# As seconds: 1656346209.5594816
# As string: Mon Jun 27 11:10:09 2022
# Seconds in the future: Wed Jun 20 04:27:47 2035
# One second behind epoch: Wed Dec 31 17:59:59 1969
from datetime import datetime, timezone
datetime_objects = list()
# A couple of common date and time representations..
dt_str_1 = '2022-06-27T13:02:30.449237+00:00' # ISO 8601, with UTC timezone
dt_str_2 = '2022-06-27T12:08:49.477587' # ISO 8601
dt_str_3 = '2022-06-27T12:00' # ISO 8601 (partial)
dt_str_4 = '2022/06/27, 11:55:23, UTC - +0000' # Custom, with UTC timezone
dt_str_5 = 'Mon Jun 27 12:09:52 2022' # Custom, without UTC timezone
dt_str_6 = 'Dec 14 2018 1:07 PM' # Custom, as AM/PM format
datetime_objects.append(datetime.fromisoformat(dt_str_1))
datetime_objects.append(datetime.fromisoformat(dt_str_2))
datetime_objects.append(datetime.fromisoformat(dt_str_3))
datetime_objects.append(datetime.strptime(dt_str_4, '%Y/%m/%d, %H:%M:%S, %Z - %z'))
datetime_objects.append(datetime.strptime(dt_str_5, '%a %b %d %H:%M:%S %Y'))
datetime_objects.append(datetime.strptime(dt_str_6, '%b %d %Y %I:%M %p'))
for dt in datetime_objects:
print("\nType: ", type(dt))
print("As str: ", dt)
print("Year: ", dt.year)
print("Timezone: ", dt.tzinfo)
# $ python3 example_2.py
# Type: <class 'datetime.datetime'>
# As str: 2022-06-27 13:02:30.449237+00:00
# Year: 2022
# Timezone: UTC
# Type: <class 'datetime.datetime'>
# As str: 2022-06-27 12:08:49.477587
# Year: 2022
# Timezone: None
# Type: <class 'datetime.datetime'>
# As str: 2022-06-27 12:00:00
# Year: 2022
# Timezone: None
# Type: <class 'datetime.datetime'>
# As str: 2022-06-27 11:55:23+00:00
# Year: 2022
# Timezone: UTC
# Type: <class 'datetime.datetime'>
# As str: 2022-06-27 12:09:52
# Year: 2022
# Timezone: None
# Type: <class 'datetime.datetime'>
# As str: 2018-12-14 13:07:00
# Year: 2018
# Timezone: None
from datetime import datetime, timedelta, timezone
# Datetime objects should be equally AWARE or NAIVE when performing
# computations (timedelta).
present = datetime.now(timezone.utc)
past = datetime(2022, 4, 23, 1, 20, 1, 141154, tzinfo=timezone.utc)
computation = present - past
time_until_EOY = datetime.fromisoformat('2023-01-01T00:00').replace(tzinfo=timezone.utc) - present
print("Data Type (present): ", type(present))
print("Data Type (past): ", type(past))
print("Data Type (computation): ", type(computation))
print("Days between present/past: ", computation.days)
print("15 days in the future: ", present + timedelta(days=15))
print("Time left until EOY: ", time_until_EOY)
# $ python3 example_3.py
# Data Type (present): <class 'datetime.datetime'>
# Data Type (past): <class 'datetime.datetime'>
# Data Type (computation): <class 'datetime.timedelta'>
# Days between present/past: 65
# 15 days in the future: 2022-07-12 23:55:40.424288+00:00
# Time left until EOY: 187 days, 0:04:19.575712
from datetime import datetime, timezone
from flask import Flask, jsonify
import psycopg2
import psycopg2.extras
# Flask Setup
app = Flask(__name__)
app.debug = True
# Database Connection
conn = psycopg2.connect(host="172.17.0.2", database="postgres", user="postgres")
def run_query(query: str):
"""
Performs a SQL query against the database.
"""
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cursor:
cursor.execute(query)
return cursor.fetchall()
def get_orders_deliveries():
"""
Fetches the orders deliveries records, reprocessing result and performing additional
time computations.
"""
data = run_query('SELECT * FROM deliveries')
deliveries = dict()
for d in data:
_id = d['id']
del d['id']
deliveries[_id] = dict(d)
deliveries[_id]['created'] = d['created'].isoformat()
deliveries[_id]['updated'] = d['updated'].isoformat()
deliveries[_id]['sent'] = d['sent'].isoformat()
if deliveries[_id]['in_transit']:
time_delta = datetime.now(timezone.utc) - deliveries[_id]['in_transit']
deliveries[_id]['in_transit_since_days'] = time_delta.days
deliveries[_id]['in_transit'] = d['in_transit'].isoformat()
return deliveries
@app.route('/api/deliveries/', methods=['GET'])
def get_deliveries():
return get_orders_deliveries()
if __name__ == '__main__':
app.run()
# $ curl http://127.0.0.1:5000/api/deliveries/
# {
# "1": {
# "created": "2022-06-20T21:52:38.198140+00:00",
# "domestic": true,
# "in_transit": null,
# "order_id": 2,
# "sent": "2022-06-25T15:41:25.478000+00:00",
# "updated": "2022-06-20T21:52:38.198140+00:00"
# },
# "2": {
# "created": "2022-06-22T21:53:36.872084+00:00",
# "domestic": true,
# "in_transit": "2022-06-24T17:22:27.047000+00:00",
# "in_transit_since_days": 3,
# "order_id": 3,
# "sent": "2022-06-23T19:35:45.447560+00:00",
# "updated": "2022-06-22T21:53:36.872084+00:00"
# },
# "3": {
# "created": "2022-06-23T21:54:20.688536+00:00",
# "domestic": true,
# "in_transit": null,
# "order_id": 1,
# "sent": "2022-06-25T12:14:12.254836+00:00",
# "updated": "2022-06-23T21:54:20.688536+00:00"
# }
# }
from datetime import datetime, timezone
import logging
import requests
r = requests.get('http://127.0.0.1:5000/api/deliveries/')
data = r.json()
for _id in data:
logging.info(f"processing record {_id}")
try:
computation = (datetime.now() - datetime.strptime(data[_id]['sent'], '%Y-%m-%dT%H:%M:%S.%f%z'))
except Exception as e:
print("\n!!! An exception was generated while calculating timestamps: ", e)
finally:
computation = datetime.now(timezone.utc) - datetime.strptime(data[_id]['sent'], '%Y-%m-%dT%H:%M:%S.%f%z')
print("Order ID: ", data[_id]['order_id'])
print("Sent: ", data[_id]['sent'])
print("In transit: ", data[_id]['in_transit'])
if data[_id]['in_transit']:
print("Days since in transit: ", data[_id]['in_transit_since_days'])
print("Current date: ", datetime.now(timezone.utc))
print(f"Since sent to delivery, was {computation.days} days...")
# $ python3 api_consumer.py
# !!! An exception was generated while calculating timestamps: can't subtract offset-naive and offset-aware datetimes
# Order ID: 2
# Sent: 2022-06-25T15:41:25.478000+00:00
# In transit: None
# Current date: 2022-06-28 00:41:15.132177+00:00
# Since sent to delivery, was 2 days...
# !!! An exception was generated while calculating timestamps: can't subtract offset-naive and offset-aware datetimes
# Order ID: 3
# Sent: 2022-06-23T19:35:45.447560+00:00
# In transit: 2022-06-24T17:22:27.047000+00:00
# Days since in transit: 3
# Current date: 2022-06-28 00:41:15.132354+00:00
# Since sent to delivery, was 4 days...
# !!! An exception was generated while calculating timestamps: can't subtract offset-naive and offset-aware datetimes
# Order ID: 1
# Sent: 2022-06-25T12:14:12.254836+00:00
# In transit: None
# Current date: 2022-06-28 00:41:15.132470+00:00
# Since sent to delivery, was 2 days...
--
-- PostgreSQL database dump
--
-- Dumped from database version 13.3 (Debian 13.3-1.pgdg100+1)
-- Dumped by pg_dump version 13.5 (Ubuntu 13.5-2.pgdg20.04+1)
-- Started on 2022-06-27 19:31:47 CDT
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- TOC entry 224 (class 1259 OID 25953)
-- Name: deliveries; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.deliveries (
id integer NOT NULL,
order_id integer,
domestic boolean DEFAULT true,
created timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
sent timestamp with time zone,
in_transit timestamp with time zone
);
ALTER TABLE public.deliveries OWNER TO postgres;
--
-- TOC entry 223 (class 1259 OID 25951)
-- Name: deliveries_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE public.deliveries_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.deliveries_id_seq OWNER TO postgres;
--
-- TOC entry 3004 (class 0 OID 0)
-- Dependencies: 223
-- Name: deliveries_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE public.deliveries_id_seq OWNED BY public.deliveries.id;
--
-- TOC entry 2860 (class 2604 OID 25956)
-- Name: deliveries id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.deliveries ALTER COLUMN id SET DEFAULT nextval('public.deliveries_id_seq'::regclass);
--
-- TOC entry 2998 (class 0 OID 25953)
-- Dependencies: 224
-- Data for Name: deliveries; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.deliveries (id, order_id, domestic, created, updated, sent, in_transit) FROM stdin;
1 2 t 2022-06-20 21:52:38.19814+00 2022-06-20 21:52:38.19814+00 2022-06-25 15:41:25.478+00 \N
3 1 t 2022-06-23 21:54:20.688536+00 2022-06-23 21:54:20.688536+00 2022-06-25 12:14:12.254836+00 \N
2 3 t 2022-06-22 21:53:36.872084+00 2022-06-22 21:53:36.872084+00 2022-06-23 19:35:45.44756+00 2022-06-24 17:22:27.047+00
\.
--
-- TOC entry 3005 (class 0 OID 0)
-- Dependencies: 223
-- Name: deliveries_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('public.deliveries_id_seq', 3, true);
--
-- TOC entry 2865 (class 2606 OID 25961)
-- Name: deliveries deliveries_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.deliveries
ADD CONSTRAINT deliveries_pkey PRIMARY KEY (id);
--
-- TOC entry 2866 (class 2606 OID 25962)
-- Name: deliveries deliveries_order_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.deliveries
ADD CONSTRAINT deliveries_order_id_fkey FOREIGN KEY (order_id) REFERENCES public.orders(id);
-- Completed on 2022-06-27 19:31:47 CDT
--
-- PostgreSQL database dump complete
--
--
-- PostgreSQL database dump
--
-- Dumped from database version 13.3 (Debian 13.3-1.pgdg100+1)
-- Dumped by pg_dump version 13.5 (Ubuntu 13.5-2.pgdg20.04+1)
-- Started on 2022-06-27 19:31:12 CDT
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- TOC entry 222 (class 1259 OID 25936)
-- Name: orders; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.orders (
id integer NOT NULL,
product_id integer,
code character varying(128) NOT NULL,
address character varying(256) NOT NULL,
fast_delivery boolean DEFAULT false,
max_dtd smallint DEFAULT 7,
created timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
ALTER TABLE public.orders OWNER TO postgres;
--
-- TOC entry 221 (class 1259 OID 25934)
-- Name: orders_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE public.orders_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.orders_id_seq OWNER TO postgres;
--
-- TOC entry 3005 (class 0 OID 0)
-- Dependencies: 221
-- Name: orders_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE public.orders_id_seq OWNED BY public.orders.id;
--
-- TOC entry 2860 (class 2604 OID 25939)
-- Name: orders id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.orders ALTER COLUMN id SET DEFAULT nextval('public.orders_id_seq'::regclass);
--
-- TOC entry 2999 (class 0 OID 25936)
-- Dependencies: 222
-- Data for Name: orders; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.orders (id, product_id, code, address, fast_delivery, max_dtd, created, updated) FROM stdin;
1 1 20200626-fda Sta. Barbara Ave. n84, San Francisco/CA - USA f 7 2022-06-24 21:38:08.110727+00 2022-06-24 21:38:08.110727+00
3 2 20200624-xsa Saint Mary Street, N 25, Las Vegas/NV - USA f 7 2022-06-24 21:42:55.90921+00 2022-06-24 21:42:55.90921+00
2 1 20200626-aab George Washington Street, N 411, Austin/TX - USA f 7 2022-06-24 21:39:09.600678+00 2022-06-24 21:39:09.600678+00
4 3 20200625-def New England Avenue, N559, Jackson/MS - USA f 7 2022-06-24 21:45:22.872025+00 2022-06-24 21:45:22.872025+00
\.
--
-- TOC entry 3006 (class 0 OID 0)
-- Dependencies: 221
-- Name: orders_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('public.orders_id_seq', 4, true);
--
-- TOC entry 2866 (class 2606 OID 25945)
-- Name: orders orders_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.orders
ADD CONSTRAINT orders_pkey PRIMARY KEY (id);
--
-- TOC entry 2867 (class 2606 OID 25946)
-- Name: orders orders_product_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.orders
ADD CONSTRAINT orders_product_id_fkey FOREIGN KEY (product_id) REFERENCES public.products(id);
-- Completed on 2022-06-27 19:31:12 CDT
--
-- PostgreSQL database dump complete
--
--
-- PostgreSQL database dump
--
-- Dumped from database version 13.3 (Debian 13.3-1.pgdg100+1)
-- Dumped by pg_dump version 13.5 (Ubuntu 13.5-2.pgdg20.04+1)
-- Started on 2022-06-27 19:30:58 CDT
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- TOC entry 220 (class 1259 OID 25893)
-- Name: products; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.products (
id integer NOT NULL,
name character varying(128) NOT NULL,
price integer NOT NULL,
created timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated timestamp with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
);
ALTER TABLE public.products OWNER TO postgres;
--
-- TOC entry 219 (class 1259 OID 25891)
-- Name: products_id_seq; Type: SEQUENCE; Schema: public; Owner: postgres
--
CREATE SEQUENCE public.products_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.products_id_seq OWNER TO postgres;
--
-- TOC entry 3002 (class 0 OID 0)
-- Dependencies: 219
-- Name: products_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: postgres
--
ALTER SEQUENCE public.products_id_seq OWNED BY public.products.id;
--
-- TOC entry 2860 (class 2604 OID 25896)
-- Name: products id; Type: DEFAULT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.products ALTER COLUMN id SET DEFAULT nextval('public.products_id_seq'::regclass);
--
-- TOC entry 2996 (class 0 OID 25893)
-- Dependencies: 220
-- Data for Name: products; Type: TABLE DATA; Schema: public; Owner: postgres
--
COPY public.products (id, name, price, created, updated) FROM stdin;
1 Notebook 600 2022-06-24 20:45:59.308879+00 2022-06-24 20:45:59.308879+00
2 Smart TV 500 2022-06-24 20:46:37.581089+00 2022-06-24 20:46:37.581089+00
3 Refrigerator 350 2022-06-24 21:44:23.902587+00 2022-06-24 21:44:23.902587+00
\.
--
-- TOC entry 3003 (class 0 OID 0)
-- Dependencies: 219
-- Name: products_id_seq; Type: SEQUENCE SET; Schema: public; Owner: postgres
--
SELECT pg_catalog.setval('public.products_id_seq', 3, true);
--
-- TOC entry 2864 (class 2606 OID 25900)
-- Name: products products_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.products
ADD CONSTRAINT products_pkey PRIMARY KEY (id);
-- Completed on 2022-06-27 19:30:58 CDT
--
-- PostgreSQL database dump complete
--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment