python: add timezone to time variable TUC to (UTC+2) - python

Im using docker to deploy. In my code
timestamp = "{:_%Y_%m_%d_%H_%M_%S}".format(datetime.now())
When i printed date of the container used i found that is in UTC.
DOes anyone knows how to modify this row code to add the timezone please ?

to get UTC now, simply use
from datetime import datetime, timezone
timestamp = "{:_%Y_%m_%d_%H_%M_%S}".format(datetime.now(tz=timezone.utc))
no need for an external library.

You are generating datetime object without any timezone info and so is assumed to be in UTC format
You need to pass in the needed timezone to datetime.now() call and adjust the format string to include timezone info
Python >= 3.9
From python 3.9 you have built-in support for timezones with zoneinfo.ZoneInfo class
>>> from zoneinfo import ZoneInfo
>>> tz = ZoneInfo("Europe/London")
>>> timestamp = "{:_%Y_%m_%d_%H_%M_%S %Z}".format(datetime.now(tz))
>>> timestamp
'_2020_08_19_15_26_25 BST'
Python < 3.9
Install pytz (pip install pytz) for timezone support
>>> import pytz
>>> tz = pytz.timezone('Europe/London')
>>> timestamp = "{:_%Y_%m_%d_%H_%M_%S %Z}".format(datetime.now(tz))
>>> timestamp
'_2020_08_18_13_44_22 BST'

Related

How to convert date string to a datetime object in a specified timezone

I can convert a given date string formatted in YYYY-MM-DD to a datetime object using:
from datetime import datetime
dt = datetime.strptime(date_str, '%Y-%m-%d')
However, this uses the current machine's timezone by default.
Is there a way to specify a specific timezone (such as UTC, PST, etc) in the conversion so that the obtained datetime object is in that timezone.
I am trying to do this in Python 3.4.3.
This is not possible using only Python's standard library.
For full flexibility, install python-dateutil and pytz and run:
date_str = '2015-01-01'
dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str))
This gives you a datetime with Europe/London timezone.
If you only need parsing of '%Y-%m-%d' strings then you only need pytz:
from datetime import datetime
naive_dt = datetime.strptime(date_str, '%Y-%m-%d')
dt = pytz.timezone('Europe/London').localize(naive_dt)

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 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

Timezone not available in python, but the system timezone is properly set

As specified in the documentation:
%Z -> Time zone name (no characters if no time zone exists).
According to date, my system has the time zone properly set:
gonvaled#pegasus ~ » date
Sat Sep 28 09:14:29 CEST 2013
But this test:
def test_timezone():
from datetime import datetime
dt = datetime.now()
print dt.strftime('%Y-%m-%d %H:%M:%S%Z')
test_timezone()
Produces:
gonvaled#pegasus ~ » python test_timezone.py
2013-09-28 09:19:10
Without time zone information. Why is that? How can I force python to output time zone info?
I have also trying re-configuring the time zone with tzselect, but has not helped.
Standard Python datetime.datetime() objects do not have a timezone object attached to them. The system time is taken as is.
You'll need to install Python timezone support in the form of the pytz package; timezone definitions change too frequently to be bundled with Python itself.
pytz does not tell you what timezone your machine has been configured with. You can use the python-dateutil module for that; it has a dateutil.tz.gettz() function that returns the timezone currently in use. This is much more reliable than what Python can get from the limited C API:
>>> import datetime
>>> from dateutil.tz import gettz
>>> datetime.datetime.now(gettz())
datetime.datetime(2013, 9, 28, 8, 34, 14, 680998, tzinfo=tzfile('/etc/localtime'))
>>> datetime.datetime.now(gettz()).strftime('%Y-%m-%d %H:%M:%S%Z')
'2013-09-28 08:36:01BST'

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")

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