Skip to content Skip to sidebar Skip to footer

Python: Strftime A Utc Timestamp To Local Time Format

I'd like to use the timestamp from a database result and convert it to my locale time format. The timestamp itself is saved in UTC format: 2015-03-30 07:19:06.746037+02. After call

Solution 1:

In your question the timestamp is already in desired timezone, so you don't need to do anything.

If you want to convert it to some other timezone you should be able to use;

YourModel.datetime_column.op('AT TIME ZONE')('your timezone name')

or,

func.timezone('your timezone name', YourModel.datetime_column)

in SQLAlchemy level.

On python level, consider using pytz

Solution 2:

You don't need to do conversions manually when you use time zone aware database timestamps unless the timezone you want to display is different from the system timezone. When you read and write datetime objects to the database the timezone info of the datetime object is taken into account, this means what you get back is the time in the local time zone, in your case +0200.

Solution 3:

This SO post answers how to get local time from a timezoned timestamp.

Basically, use tzlocal.

import time
from datetime import datetime

import pytz # $ pip install pytzfrom tzlocal import get_localzone # $ pip install tzlocal# get local timezone    
local_tz = get_localzone() 

# test it# utc_now, now = datetime.utcnow(), datetime.now()
ts = time.time()
utc_now, now = datetime.utcfromtimestamp(ts), datetime.fromtimestamp(ts)

local_now = utc_now.replace(tzinfo=pytz.utc).astimezone(local_tz) # utc -> localassert local_now.replace(tzinfo=None) == now

Post a Comment for "Python: Strftime A Utc Timestamp To Local Time Format"