How to use python to take UTC datetime, auto-detect users timezone and convert date-time to the desired format?

There are tons of questions about time and time conversions, and there seems to be no consensus on the β€œbest way.”

Accordingly: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ , pytz is the best way. it shows a timezone conversion like this datetime.datetime.utcnow().replace(tzinfo=pytz.utc) , but it doesn't say how to get a custom timezone ...

This guy https://stackoverflow.com >

Everyone I see using pytz with has their own timezone ( users_timezone = timezone("US/Pacific") ), which I don’t understand, because you can’t know if your viewer is there ...

This guy, https://stackoverflow.com/a/168269/ has a way to automatically detect time zones, but it uses the dateutil library, not pytz, as recommended by both Armin Ronacher and official python docs ( http: //docs.python. org / library / datetime.html # strftime-and-strptime-behavior , just above this anchor in the yellow field)

All I need is the simplest, most reliable future, all daylight saving time / etc, considered as a way to take my stamp datetime.utcnow () ( 2012-08-25 10:59:56.511479 ), convert it to the user's time zone. And show it like this:

 Aug 25 - 10:59AM 

and if the year is not this year, I would say

 Aug 25 '11 - 10:59AM 
+6
source share
1 answer

ok, here it is (also my first contribution to SO :))

this requires 2 external libraries that may discard some of them ...

 from datetime import datetime from dateutil import tz import pytz def standard_date(dt): """Takes a naive datetime stamp, tests if time ago is > than 1 year, determines user local timezone, outputs stamp formatted and at local time.""" # determine difference between now and stamp now = datetime.utcnow() diff = now - dt # show year in formatting if date is not this year if (diff.days / 365) >= 1: fmt = "%b %d '%y @ %I:%M%p" else: fmt = '%b %d @ %I:%M%p' # get users local timezone from the dateutils library # http://stackoverflow.com/a/4771733/523051 users_tz = tz.tzlocal() # give the naive stamp timezone info utc_dt = dt.replace(tzinfo=pytz.utc) # convert from utc to local time loc_dt = utc_dt.astimezone(users_tz) # apply formatting f = loc_dt.strftime(fmt) return f 
+3
source

Source: https://habr.com/ru/post/923735/


All Articles