Python: strftime a UTC timestamp to local time format - python

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 calling print value.strftime(format) with the format %d.%m.%Y %H:%M %z the output will be 30.03.2015 07:19 +0200. This might be the correct way to display timestamps with timezone information but unfortunately users here are not accustomed to that. What I want to achieve is the following for the given timestamp: 30.03.2015 09:19. Right now I'm adding two hours via
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (tine.altzone if is_dst else time.timezone)
value = value + timedelta(seconds=utc_offset)
I was wondering if there is a more intelligent solution to my problem. (timestamp.tzinfo has a offset value, can/should this be used instead? The solution needs to be DST aware too.)

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

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.

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 pytz
from 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 -> local
assert local_now.replace(tzinfo=None) == now

Related

I am Not able to convert the unix time to local date and time in PYTHON

I wanted to convert the UNIX time into local date and time. I am getting the UNIX timestamp value from my server but when I convert the UNIX using these set of code I get a time which is 1 hour 30 min less than the actual time. But when I take the raw timestamp data and check in the online UNIX to local date and time converter I get the correct time.
import datetime
time_local = datetime.datetime.fromtimestamp(1502705627085/1e3)
print time_local
is your timezone correct on your system ?
From the python datetime documentation :
classmethod datetime.fromtimestamp(timestamp[, tz])
Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
If you cannot change your system's timezone, you can specify a tz as explained in the datetime module documentation.
import datetime
import tzlocal
time_local = datetime.datetime.fromtimestamp(1502705627085/1e3, tzlocal.get_localzone())
print time_local

Local Time To UTC time pytz

I converted python datetime with help of pytz.
Convertion is like this
2013-08-23T09:53:03 to 2013-08-23T15:23:03+05:30 (time is changed
according timezone)
now the problem is "At at another loaction i get time as string 2013-08-23T15:23:03+05:30 how can i convert this string to 2013-08-23T09:53:03
thanks in advance
You can use the very useful dateutil package
from dateutil import parser
import pytz
UTC = pytz.timezone('UTC')
date = parser.parse("2013-08-23T15:23:03+05:30")
dateutc = date.astimezone(UTC)
print dateutc.isoformat()
# or user strptime to have in the format you want (without time zone)
print dateutc.strftime("%Y-%m-%dT%H:%M:%S")

How to pick a timezone based on UTC offset?

i've got a silly problem. I'm parsing Facebook user data, and I get the timezone as a number:
timezone: The user's timezone offset from UTC
For me ('America/Argentina/Buenos_Aires') it's -3.
Now, how can I convert that number to a pytz.timezone?
Thank you!
There's not a 1:1 correspondence, so there's no way to do it without making some assumptions that are bound to be invalid.
You can create your own tzinfo class that encodes the offset directly without trying to tie it back to a zone.
As #Mark Ransom said, multiple pytz.timezone may have the same UTC offset at a given date. You could print the mapping for a particular date:
#!/usr/bin/env python
from collections import defaultdict
from datetime import datetime
import pytz # $ pip install pytz
dt = datetime.now(pytz.utc) # current time in UTC
zone_names = defaultdict(list)
for tz in pytz.common_timezones:
zone_names[dt.astimezone(pytz.timezone(tz)).utcoffset()].append(tz)
for offset, zone in sorted(zone_names.items()):
print("%.1f %s" % (offset.total_seconds() / 3600, zone))
# -> -11.0 ['Pacific/Midway', 'Pacific/Niue', 'Pacific/Pago_Pago']
# ...
You can use tzinfo.tzname to get the zone name.

Converting datetime.time() intho the same format as time.time()

I'm using the following to get utc datetime:
import datetime
import time
from pytz import timezone
now_utc = datetime.datetime.now(timezone('UTC'))
now = time.time()
print now_utc.time(), now
>> 04:51:39.337515 1332823899.34
I need to convert the format of now_utc.time() to look like the output of time.time().
How do I do that? Or, how to I get time.time() in utc?
time.mktime(now_utc.timetuple())
Updating the answer, since it was completely wrong, but mistake I made can be useful for others.
time.mktime does not retain the timezone, using the tuple as a local time, so this:
time.mktime(datetime.now().timetuple())
would rather work.
But, to make it short, time.time(), as explicitly stated in the spec, returns an UTC timestamp, so just use it.
(Also, you don't need pytz to get an UTC datetime, datetime.utcnow() does the same)
try:
now_utc.time().strftime(....)
from here

Change datetime to Unix time stamp in Python

Please help me to change datetime object (for example: 2011-12-17 11:31:00-05:00) (including timezone) to Unix timestamp (like function time.time() in Python).
Another way is:
import calendar
from datetime import datetime
d = datetime.utcnow()
timestamp=calendar.timegm(d.utctimetuple())
Timestamp is the unix timestamp which shows the same date with datetime object d.
import time
import datetime
dtime = datetime.datetime.now()
ans_time = time.mktime(dtime.timetuple())
Incomplete answer (doesn't deal with timezones), but hopefully useful:
time.mktime(datetime_object.timetuple())
** Edited based on the following comment **
In my program, user enter datetime, select timezone. ... I created a timezone list (use pytz.all_timezones) and allow user to chose one timezone from that list.
Pytz module provides the necessary conversions. E.g. if dt is your datetime object, and user selected 'US/Eastern'
import pytz, calendar
tz = pytz.timezone('US/Eastern')
utc_dt = tz.localize(dt, is_dst=True).astimezone(pytz.utc)
print calendar.timegm(utc_dt.timetuple())
The argument is_dst=True is to resolve ambiguous times during the 1-hour intervals at the end of daylight savings (see here http://pytz.sourceforge.net/#problems-with-localtime).

Categories

Resources