Pages

Sunday, November 22, 2026

Parsing UK order dates in Python without swapping day and month

Two order exports can contain the same value, 03/04/2026, and mean different things. A day-first export means 3 April. A month-first export means 4 March. Both are valid calendar dates, so trying one parser and falling back to the other only works when the first parser fails. It cannot resolve this case.

Choose the format from the source

Get the date format from the supplier's export specification or your own import configuration. The example below assumes one known exporter consistently uses DD/MM/YYYY and another uses MM/DD/YYYY. An export's country label by itself is not a format guarantee.

import re
from datetime import datetime

DATE_FORMATS = {"uk_export": "%d/%m/%Y", "us_export": "%m/%d/%Y"}
DATE_SHAPE = re.compile(r"[0-9]{2}/[0-9]{2}/[0-9]{4}")


def order_date(raw, source):
    if source not in DATE_FORMATS:
        raise ValueError("unknown source date format")
    if not DATE_SHAPE.fullmatch(raw):
        raise ValueError("expected two digits, slash, two digits, slash, four digits")
    return datetime.strptime(raw, DATE_FORMATS[source]).date().isoformat()


print(order_date("03/04/2026", "uk_export"))
print(order_date("03/04/2026", "us_export"))

Output with Python 3.12:

2026-04-03
2026-03-04

The regular expression enforces the shape promised by these exporters. Python's strptime() checks the calendar date and accepts an optional leading zero for day and month on its own. For this strict contract, 3/4/2026 is rejected by the shape check; 31/04/2026 passes that check but is rejected by the date parser.

Keep rows you cannot interpret out of the report

Record the row identifier, original date and reason in an exception report rather than silently changing formats. Ask the supplier to confirm the format, or request YYYY-MM-DD for future date-only exports. Treat timestamps with times and offsets as a separate input contract.

References: Python format-code documentation. For general background, see Howcodex’s Python 3 date and time guide. This post is shared on behalf of Howcodex.

Saturday, November 21, 2026

Python zip(strict=True) Can Raise After You've Already Written Two Rows

Suppose an export gives you three order IDs and a separate file gives you two amounts in cents. If you pair them with ordinary zip(), Python stops at the shorter input. The third order disappears from the output.

order_ids = ["A-101", "A-102", "A-103"]
amounts = [1299, 2499]

print(list(zip(order_ids, amounts)))
# [('A-101', 1299), ('A-102', 2499)]

Python 3.10 added strict=True to catch this mismatch. The catch is timing: zip() is lazy. It yields the first two pairs before the next iteration raises ValueError.

written = []

try:
    for row in zip(order_ids, amounts, strict=True):
        written.append(row)  # Stand-in for a write.
except ValueError:
    print(written)
    # [('A-101', 1299), ('A-102', 2499)]

Breaking early also skips the check on the unread part of the input. Turning on strict mode doesn't validate the whole batch upfront.

For a small batch, check first and write second

Consume the iterator before calling the writer. If the list construction fails, execution never reaches outbox.extend().

outbox = []

try:
    batch = list(zip(order_ids, amounts, strict=True))
except ValueError:
    assert outbox == []
else:
    outbox.extend(batch)

This protects the writer from an input-length mismatch. It doesn't make the writer itself atomic, and consuming an iterator can still advance or trigger side effects in that iterator.

For a larger import, put SQLite writes in a transaction

In Python 3.12+, sqlite3.connect(..., autocommit=False) lets a connection's with block commit on success or roll back when an exception escapes. Catch the error outside the block. In this example, two inserts are attempted before the length mismatch, but neither row remains.

import sqlite3

con = sqlite3.connect(":memory:", autocommit=False)
try:
    con.execute("CREATE TABLE orders (id TEXT PRIMARY KEY, cents INTEGER)")
    con.commit()

    try:
        with con:
            con.executemany(
                "INSERT INTO orders VALUES (?, ?)",
                zip(order_ids, amounts, strict=True),
            )
    except ValueError:
        assert con.execute("SELECT COUNT(*) FROM orders").fetchone() == (0,)
finally:
    con.close()

That rollback covers writes in this database transaction. It can't undo an email, file write, or API request. If the two exports can arrive in a different order, join them by order ID and check for duplicate and missing IDs. Two columns of the same length can still pair the wrong records.

References: Python zip documentation, PEP 618, and SQLite connection context manager.

Related reading from the site behind this post: Howcodex’s Python SQLite tutorial collection.

Friday, November 20, 2026

Python PATCH updates: Tell a missing nickname from null

A partial profile update has three meanings: an omitted nickname leaves the old one alone, JSON null clears it, and a string replaces it, including an empty string. Plain patch.get("nickname") returns None for the first two cases.

Use a private placeholder as the default and compare it by identity:

import json

MISSING = object()


def apply_nickname_patch(current, body):
    patch = json.loads(body)
    if not isinstance(patch, dict):
        raise ValueError("Expected a JSON object")

    nickname = patch.get("nickname", MISSING)
    if nickname is MISSING:
        return current
    if nickname is None or isinstance(nickname, str):
        return nickname
    raise ValueError("nickname must be a string or null")


assert apply_nickname_patch("Maple", '{}') == "Maple"
assert apply_nickname_patch("Maple", '{"nickname": null}') is None
assert apply_nickname_patch("Maple", '{"nickname": "Fern"}') == "Fern"
assert apply_nickname_patch("Maple", '{"nickname": ""}') == ""

Check is MISSING first. A truthiness check would lump None and "" together. Keep the placeholder inside Python and create it only once.

This is one endpoint's contract, not a complete JSON Merge Patch implementation. In Python 3.15, the built-in sentinel() provides an alternative: MISSING = sentinel("MISSING"). Reuse the same instance. The four assertions above passed with object() on Python 3.12 and 3.13; the newer alternative was checked against the documentation, not executed here.

Shared on behalf of Howcodex.

Thursday, November 19, 2026

In Python, subtract UTC instants to measure elapsed time

A support shift in New York starts at 00:30 and ends at 03:30 on the morning the clocks fall back. The wall clock shows a three-hour difference, but the shift lasts four hours. Subtracting the local Python datetimes directly can quietly give you the wrong duration.

Reproduce the difference

Use Python 3.9 or newer. If your machine lacks an IANA time-zone database, install Python's first-party tzdata package in the project environment.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")
utc = timezone.utc
start = datetime(2025, 11, 2, 0, 30, tzinfo=ny)
end = datetime(2025, 11, 2, 3, 30, tzinfo=ny)

wall_clock = end - start
elapsed = end.astimezone(utc) - start.astimezone(utc)
print(start.isoformat(), "→", end.isoformat())
print("Wall-clock difference:", wall_clock)
print("Elapsed duration:", elapsed)
assert wall_clock == timedelta(hours=3)
assert elapsed == timedelta(hours=4)

The first line shows the offset changing from UTC−04:00 to UTC−05:00. The next two lines report 3:00:00 and 4:00:00, respectively. When two aware datetime values have the same tzinfo object, subtraction ignores that object. Convert the endpoints to UTC before subtracting to measure elapsed time.

Disambiguate the repeated hour

At 01:15 that morning, the local reading occurs twice. Use fold=0 for the first occurrence and fold=1 for the second.

first = datetime(2025, 11, 2, 1, 15, tzinfo=ny, fold=0)
second = first.replace(fold=1)
assert first.utcoffset() == timedelta(hours=-4)
assert second.utcoffset() == timedelta(hours=-5)
assert second.astimezone(utc) - first.astimezone(utc) == timedelta(hours=1)

For completed events, store the UTC instant and convert it for display. For an appointment that follows local time, retain the date, time and zone name. Ask which occurrence the person means if the time is repeated, and separately validate times skipped in spring; attaching ZoneInfo does not perform that validation.

References: Python datetime arithmetic and Python zoneinfo and fold.


Site affiliation: Howcodex is operated by the account sharing this standalone, tested example.

Thursday, July 3, 2014

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA


Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Posted: 03 Jul 2014 07:00 AM PDT

Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA

Every entrepreneur knows that starting a business is never an easy feat, but starting your business in America is said to be particularly challenging. While there may be challenges to business here in the states, there are plenty of advantages and opportunities, too. While some may find that sourcing your business abroad is the best course of action, there are many entrepreneurs who want to create their products and services at home in their local communities across America.

To help you understand some of the challenges and opportunities of making a business in America, here are three entrepreneurs who are choosing to stay Made in the USA.

Dodocase

DoDo Case, San Francisco, CA

Challenge: American Skilled Labor Costs

Opportunity: Save On Outsourced Manufacturing Costs

DODOcase has combined the craftsmanship of traditional bookbinding with the needs of a modern digital market, to create beautiful, one-of-a-kind iPod and iPad cases. Each DODOcase item is handmade by a local craftsman in their San Fran headquarters. But isn't all that skilled American labor too expensive. Co-founder of DODOcase, Patrick Buckley explained that while the perception often is that the cost of labor it too high, by manufacturing in-house, DODOcase is actually able to tighten up their supply cycle.

Things happen faster because they aren't waiting for outside vendors or overseas manufacturers and they don't have the extra shipping or foreign trade costs. Doing the real cost benefit analysis on domestic labor could end up surprising you. Don't rule skilled American labor out before you do the research.
Printful Logo

Printful, Burbank, CA

Challenge: Starting a US Business as a Foreign-National

Opportunity: Access to Resources and Skilled Labor

Printful offers automatic and on-demand printing fulfillment service that range from posters to greeting cards to mugs -- all designed to help make printing costs transparent and affordable to the small to medium sized online business. Perhaps even more unique than PRINTFUL being based in Burbank, California, is the fact that it has been co-founded in 2013, by Lauris Liberts, a Latvian born entrepreneur, who also co-founder of a Latvian social network Draugiem(.lv).

But isn't starting a business in the US, especially in California expensive? Wouldn't it be cheaper to start the business back in Latvia?

Lauris says that while the cost of doing business might be a bit higher in the US, the opportunities here far outweighed the monetary considerations. He said that while there were certainly challenges getting started, the access to technology, the skilled and educated labor force and the culture of innovation that permeate California made it the perfect culmination of business market factors he was looking for to start PRINTFUL. By providing businesses with options for one-off and on-demand printing with no subscription fees required, the company has really taken off, while helping small online businesses flourish, too.

There's more to starting your business than just costs: consider the market factors and culture your business will need to thrive.

Buck Knives Logo

Buck Knives,

Challenge: Outsourcing Backlash

Opportunity: American Made Builds A Brand

BUCK KNIVES. Founded back in the early part of the century, they made all their knives here in America. However, with the rising cost of domestic skilled labor, they took a gamble and starting outsourcing about 30% of their knife manufacturing to China. With a huge backlash! Customers didn't want Buck Knives made in China. They were willing to pay a higher price to keep that quality MADE IN THE USA. How could your brand be hurt by outsourcing overseas? With a century long history of being Made in the USA, outsourcing their manufacturing to China hurt the Buck brand. So after the stint in offshore manufacturing, Buck Knives returned 100% of their business to being made in Idaho. American labor could be an important part of your brand. Know the costs of outsourced labor before you decide.

The post Made in America: 3 Entrepreneurs Who Are Making Their Businesses Work in the USA appeared first on Blogtrepreneur - The Business of Blogging For Busy Entrepreneurs.

Extra, Extra: Storm Turns Gowanus Into Aboveground Toilet

Extra, Extra: Storm Turns Gowanus Into Aboveground Toilet


Extra, Extra: Storm Turns Gowanus Into Aboveground Toilet

Posted: 03 Jul 2014 02:00 PM PDT

Extra, Extra: Storm Turns Gowanus Into Aboveground Toilet Because your dog has never driven you to the store, check out today's end-of-day links: penny skirt trick, Gownus shit storm, hot dog sandwiches, Chris Martin meat-eater, World Cup of arm folding, creepy Ben Stein, depressed animals, and kitty plays with dog. Don't forget to follow Gothamist on Twitter and like us on Facebook. You can also get the top stories mailed to you—sign up here. [ more › ]






Video: De Blasio Unleashes Dad Puns At Hot Dog Eating Contest Weigh-In

Posted: 03 Jul 2014 01:50 PM PDT

    
Mayor de Blasio waded awkwardly into the seas of pundom today during his speech at the weighing-in ceremony for tomorrow's Nathan's Famous 4th of July Hot Dog Eating Contest. Arguably better than Darth Vader's performance last year, de Blaz and/or his speechwriters let fly with a string of condiment and cased meat entendres while introducing Joey Chesnut, Miko Sudo, and the rest of tomorrow's gluttonous gladiators. [ more › ]






Some Williamsburg, Greenpoint Waterfront Areas Will Be Closed For July 4th

Posted: 03 Jul 2014 01:40 PM PDT

Some Williamsburg, Greenpoint Waterfront Areas Will Be Closed For July 4th A reader noticed this sign indicating that parts of the Williamsburg waterfront would be closed starting tonight through July 5 morning. [ more › ]






Obamacare Insurer Eyeing Big Price Hike In 2015

Posted: 03 Jul 2014 01:25 PM PDT

Obamacare Insurer Eyeing Big Price Hike In 2015 Now that everyone's finally stopped bitching about how hard it was to sign up for healthcare through the Affordable Care Act, we can all start complaining about how expensive it's going to be. MetroPlus, one of Obamacare's most popular insurers in New York State, is reportedly looking to jack its premiums for individuals up by an average of 18.5 percent in 2015, with small group plans facing a 30 percent hike. Still less than surgery without insurance, but damn. [ more › ]






Man Killed After Falling On Tracks While Switching Between Subway Cars

Posted: 03 Jul 2014 12:57 PM PDT

Man Killed After Falling On Tracks While Switching Between Subway Cars A 30-year-old man died after falling onto the subway tracks while trying to switch between cars. According to the MTA, the incident happened just before 10 p.m. during last night's storm, when the as-yet unidentified man fell onto the northbound R train tracks near the 25th Street Station in Brooklyn. The man was reportedly moving between subway cars at the time. [ more › ]






Photo: Lindsay Lohan Cut Her Leg On A Citibike

Posted: 03 Jul 2014 12:47 PM PDT

Photo: Lindsay Lohan Cut Her Leg On A Citibike Lindsay Lohan, who only somehow just turned 28 this week, was injured while riding a Citibike. Or maybe docking a Citibike. Or maybe while looking at a Citibike. Maybe a nest of Citibikes attacked her. It's all very unclear at press time, but Lohan—who has taken the royal blue chariots out for a spin in the past—Instagrammed this photo of her cut leg, with the caption: "A citibike gone wrong #notsoquiche !!!!" What does that hashtag mean? Maybe it holds the meaning to this mystery. [ more › ]






Photos: Woman Jumps Into Prospect Park Lake—For Her Dog!

Posted: 03 Jul 2014 12:14 PM PDT

 
Earlier this morning, a woman had to be rescued after apparently getting stuck on an island in Prospect Park's lake. And why did she go over the island? To chase her dog, which had been swimming in the lake. [ more › ]






ReBar Fraudster Jason Stevens Banned From NY Restaurant Industry For Life

Posted: 03 Jul 2014 11:55 AM PDT

ReBar Fraudster Jason Stevens Banned From NY Restaurant Industry For Life Earlier this month, infamous reBar owner Jason Stevens agreed to a plea deal that ensures he'll spend 3 1/3 to 10 years in prison for tax fraud. Stevens pled guilty to grand larceny and four counts of criminal tax fraud in the second degree after he allegedly didn't pay millions of dollars in taxes over the last couple years. And now, Stevens has been formally banned for life from the NY restaurant and catering industry. [ more › ]






Video: Sleeping Man Arrested On Nearly Empty F Train

Posted: 03 Jul 2014 11:20 AM PDT

Video: Sleeping Man Arrested On Nearly Empty F Train A YouTube video of a man being arrested on an F train for allegedly falling asleep during his early morning commute has been making the rounds on the Internet. According to the NYPD, which confirmed the arrest, the unidentified individual was "occupying more than one seat," which is a violation of the MTA's rules of conduct. [ more › ]






Photos: Creepy Crawly Spiders Now At The AMNH

Posted: 03 Jul 2014 10:57 AM PDT

 
When encountering black widow spiders in NYC, it's probably best to do so at the iconic American Museum of Natural History, with some impenetrable glass separating you. Their annual Spiders Alive! exhibition is back, starting tomorrow and running through [ more › ]






Original Dirt Candy To Close In August Before Moving To LES

Posted: 03 Jul 2014 10:27 AM PDT

Original Dirt Candy To Close In August Before Moving To LES Chef Amanda Cohen's tiny vegetable-driven restaurant Dirt Candy will close at the end of August...before reopening in a (larger) space on the Lower East Side! How refreshing to write about a restaurant closing without the usual doom and gloom and rent hike ranting! [ more › ]






Williamsburg's Kings Pharmacy Is Closing

Posted: 03 Jul 2014 09:49 AM PDT

Williamsburg's Kings Pharmacy Is Closing And so continues Williamsburg's sad chainsformation—Kings Pharmacy, an independently-owned drugstore that's been operating on Bedford Avenue for over a decade, is on its way out. [ more › ]






Lincoln Tunnel Crash Kills 3, Snarls Traffic

Posted: 03 Jul 2014 09:32 AM PDT

Lincoln Tunnel Crash Kills 3, Snarls Traffic Three people were killed in a single-vehicle crash in New Jersey this morning near the entrance of the Lincoln Tunnel, jamming traffic during commuting hours. [ more › ]






Blackout Drunk Man Arrested For Stealing Cab & Leading Cops On Chase

Posted: 03 Jul 2014 08:40 AM PDT

Blackout Drunk Man Arrested For Stealing Cab & Leading Cops On Chase A man was arrested after he allegedly punched a cabbie, stole his cab, and led cops on a foot chase on the side of the Henry Hudson Parkway. But suspect David Meck isn't really sure what did or didn't happen, because he claims he was blackout drunk at the time. [ more › ]






Teen Charged In Coney Island Double Shooting That Left 10-Year-Old Hospitalized

Posted: 03 Jul 2014 08:16 AM PDT

Teen Charged In Coney Island Double Shooting That Left 10-Year-Old Hospitalized A 19-year-old Brooklyn man has been charged with two counts of attempted murder in connection with the Coney Island double shooting that left both a 10-year-old boy and 25-year-old man hospitalized last weekend. [ more › ]






Danny Meyer Reveals Insane Rent Hike For Union Square Cafe

Posted: 03 Jul 2014 08:01 AM PDT

Danny Meyer Reveals Insane Rent Hike For Union Square Cafe It's been over a week since we learned that Danny Meyer's pioneering Union Square Cafe would leave its 29-year home at the end of next year due to a rent increase. Now the restaurateur sheds some light on the situation and wades into a deeper discussion of NYC's "problem" of rising rents and diminishing character in an op-ed for the Times. [ more › ]






Cops Say Scissors-Wielding Man Groped Female Subway Rider

Posted: 03 Jul 2014 07:35 AM PDT

Cops Say Scissors-Wielding Man Groped Female Subway Rider Police are hoping for the public's help in identifying a man accused of attacking a woman at a Brooklyn train station last month. [ more › ]






NYPD: Hit-And-Run Driver Killed 12-Yr-Old, Injured Her Mother And Sister In Brooklyn

Posted: 03 Jul 2014 07:00 AM PDT

NYPD: Hit-And-Run Driver Killed 12-Yr-Old, Injured Her Mother And Sister In Brooklyn Police are searching for a callous hit and run driver who stole a minivan and ended up hitting a family in Brooklyn. A 12-year-old girl was killed while her mother and 9-year-old sister were hospitalized. A witness said the driver was "going 120 mph." [ more › ]






Photos, Video: Last Night's Wild Lightning Show

Posted: 03 Jul 2014 05:49 AM PDT

 
Yesterday's storms were no joke—there was flash flooding, air travel delays and even a partial wall collapse by a pedestrian entrance to the Brooklyn Bridge. And it's not over—the National Weather Service warns there's more heavy rain and storms on the way. [ more › ]






Wall Under Brooklyn Bridge Collapses During Storm

Posted: 03 Jul 2014 05:25 AM PDT

Wall Under Brooklyn Bridge Collapses During Storm During last night's pounding thunderstorm, a facade under the Brooklyn Bridge on the Brooklyn side collapsed, injuring numerous people. [ more › ]