Changing time from UTC to PDT - python

This is what I have:
pat = '%Y-%m-%d %H:%M:%S +0000'
my_time = time.strptime(task_time, pattern)
But, how can I change the timezone from:
my_time:
2016-06-15 23:27:52 +0000
to a different timezone:
PDT
or
-0700
So the result is:
result = 2016-06-15 16:27:52 -0700

Using the python package arrow this simple script can be used:
import arrow
fmt = "YYYY-MM-DD HH:mm:ss Z"
time = arrow.get("2016-06-15 23:27:52 +0000", fmt)
time = time.to("US/Pacific")
print(time.format(fmt))
2016-06-15 16:27:52 -0700
Install arrow with pip install arrow
Edit: If you do not want to use the arrow package:
import time
import calendar
fmt = "%Y-%m-%d %H:%M:%S "
t = calendar.timegm(time.strptime("2016-06-15 23:27:52 +0000", fmt + "+0000"))
t -= 8 * 60 * 60
s = time.strftime(fmt + "-0700", time.gmtime(t))
print(s)
Note, that this is horrible code and if you use this in production you will definitely get fired from your job, so just install the arrow package!

Related

PYTHON: config use datetime as a parameter , but the time is not updated

```
today_current = datetime.now()
before_2hour = today_current + timedelta(hours=-2)
param = before_2hour.strftime("%Y-%m-%d %H:%M:%S"))
```
the configuration file uses datetime as a parameter, but the time is the same each time.
how to fix it
This works for me in Python 3
import datetime
today_current = datetime.datetime.now()
print(today_current.strftime("%Y-%m-%d %H:%M:%S"))
before_2hour = today_current + datetime.timedelta(hours=-2)
param = before_2hour.strftime("%Y-%m-%d %H:%M:%S")
print(param)
Giving:
$ python3 now.py
2018-09-20 13:46:35
2018-09-20 11:46:35
Is this not what you were expecting?

Python - Timezone name given timestamp UTC and UTC offset

I am trying to build a function as follows:
Input
UTC timestamp in miliseconds, for example:
1456865863633
UTC offset, or miliseconds to add/substract to the UTC timestamp to obtain the time in the corresponding timezone, for example:
-14400
OutPut
Time zone name in the following format:
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
.
.
.
I've been trying to find the rught combination to do it using datetime and pytz libraries, but I was not successful so far.
Any ideas?
You could loop through all the timezones
for name in pytz.all_timezones:
and compare the date's utcoffset to the given offset:
if date.utcoffset().total_seconds() == utcoffset:
result.append(name)
import datetime as DT
import pytz
utc = pytz.utc
def tzones(timestamp, utcoffset):
result = []
date = utc.localize(DT.datetime.utcfromtimestamp(timestamp/float(1000)))
for name in pytz.all_timezones:
timezone = pytz.timezone(name)
date = date.astimezone(timezone)
if date.utcoffset().total_seconds() == utcoffset:
result.append(name)
return result
print(tzones(1456865863633, -14400))
prints
['America/Anguilla', 'America/Antigua', 'America/Aruba', 'America/Barbados', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Campo_Grande', 'America/Cuiaba', 'America/Curacao', 'America/Dominica', 'America/Glace_Bay', 'America/Goose_Bay', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guyana', 'America/Halifax', 'America/Kralendijk', 'America/La_Paz', 'America/Lower_Princes', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Moncton', 'America/Montserrat', 'America/Port_of_Spain', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Santo_Domingo', 'America/St_Barthelemy', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Thule', 'America/Tortola', 'America/Virgin', 'Atlantic/Bermuda', 'Brazil/West', 'Canada/Atlantic', 'Etc/GMT+4']
Here's a different implementation of the approach from #unutbu's answer:
from datetime import datetime
import pytz
def timezones_from_utc_offset(offset, now=None):
if now is None:
now = datetime.now(pytz.utc)
return {tz.zone for tz in map(pytz.timezone, pytz.all_timezones_set)
if now.astimezone(tz).utcoffset() == offset}
If the input is the POSIX time in milliseconds:
>>> from datetime import timedelta
>>> dt = datetime(1970,1,1,tzinfo=pytz.utc) + timedelta(milliseconds=1456865863633)
>>> timezones_from_utc_offset(offset=timedelta(seconds=-14400), now=dt)
{'America/Anguilla',
'America/Antigua',
'America/Aruba',
'America/Barbados',
'America/Blanc-Sablon',
'America/Boa_Vista',
'America/Campo_Grande',
'America/Cuiaba',
'America/Curacao',
'America/Dominica',
'America/Glace_Bay',
'America/Goose_Bay',
'America/Grand_Turk',
'America/Grenada',
'America/Guadeloupe',
'America/Guyana',
'America/Halifax',
'America/Kralendijk',
'America/La_Paz',
'America/Lower_Princes',
'America/Manaus',
'America/Marigot',
'America/Martinique',
'America/Moncton',
'America/Montserrat',
'America/Port_of_Spain',
'America/Porto_Velho',
'America/Puerto_Rico',
'America/Santo_Domingo',
'America/St_Barthelemy',
'America/St_Kitts',
'America/St_Lucia',
'America/St_Thomas',
'America/St_Vincent',
'America/Thule',
'America/Tortola',
'America/Virgin',
'Atlantic/Bermuda',
'Brazil/West',
'Canada/Atlantic',
'Etc/GMT+4'}

Change localtime from UTC to UTC + 2 in python

How I can change this code from localtime UTC to UTC+2. Now hours() function print 13 but I need to write 15.
import time;
def hours():
localtime = time.localtime(time.time())
return localtime.tm_hour
def minutes():
localtime = time.localtime(time.time())
return localtime.tm_min
def seconds():
localtime = time.localtime(time.time())
return localtime.tm_sec
print(hours())
#minutes()
#seconds()
How about using the datetime module:
import datetime;
today = datetime.datetime.now()
todayPlus2Hours = today + datetime.timedelta(hours=2)
print(todayPlus2Hours)
print(todayPlus2Hours.hour)
print(todayPlus2Hours.minute)
print(todayPlus2Hours.second)
You can use pytz along with datetime modules.
for a timezone reference i'd look here.
I'd do something of this sort:
import datetime
import pytz
utc_dt = datetime.datetime.now(tz=pytz.utc)
amsterdam_tz = pytz.timezone("Europe/Amsterdam")
local_amsterdam_time = amsterdam_tz.normalize(utc_dt)
print local_amsterdam_time.hour
print local_amsterdam_time.minute
print local_amsterdam_time.second

How to convert datetime string without timezone to another datetime with timezone in python?

I can't seem to figure out how to convert a datetime string to another datetime string with timezone.
Here's the example.
07/27/2015:06:00 AM to 20150727060000 -0400
The default timezone would be EST.
Here's my code so far.
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
Use pytz module to work with timezones in Python. To get the local timezone as pytz tzinfo object, you could use tzlocal module:
from tzlocal import get_localzone # $ pip install tzlocal
naive = _to_datetime('07/27/2015', '06:00 AM')
aware = get_localzone().localize(naive, is_dst=None)
print(aware.strftime('%Y%m%d%H%M%S %z'))
# -> 20150727060000 -0400
Add the time zone to the parsed string with %z. This will give it a tzinfo attribute:
from datetime import datetime, timedelta
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time + ' -0400', '%m/%d/%Y:%I:%M %p %z')
Example:
>>> datetime.strptime('03/19/2015:03:00 PM -0400','%m/%d/%Y:%I:%M %p %z')
datetime.datetime(2015, 3, 19, 15, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))
You could use dateutil to add the tzinfo to the datetime object.
from datetime import datetime, timedelta
from dateutil import tz
AmericaNewYorkTz = tz.gettz('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p').replace(tzinfo=AmericaNewYorkTz)
dt = _to_datetime('07/27/2015', '06:00 AM')
print('DateTime:', dt)
# DateTime: 2015-07-27 06:00:00-04:00
or as J.H. Sebastian pointed out, you can use pytz
from datetime import datetime, timedelta
from pytz import timezone
AmericaNewYorkTz = timezone('America/New_York')
def _to_datetime(air_date, air_time):
schedule_time = '{}:{}'.format(air_date, air_time)
naiveDateTime = datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
localizedDateTime = AmericaNewYorkTz.localize(naiveDateTime, is_dst=None)
return localizedDateTime
dt = _to_datetime('05/27/2015', '06:00 AM')
print('DateTime:', dt)

Convert Time Zone + format in Python from Twitter API

In Python, with TwitterSearch, I'm able to get the timestamp of the tweet in UTC time, in the following format :
Thu Mar 19 12:37:15 +0000 2015
However, I would like to obtain it automatically in the EST timezone (UTC - 4), in this format :
2015-03-19 08:37:15
Here is a sample of my code. What should I change in it for an automatic conversion?
for tweet in ts.search_tweets_iterable(tso):
lat = None
long = None
user = tweet['user']['screen_name']
user_creation = tweet['user']['created_at']
created_at = tweet['created_at'] # UTC time when Tweet was created.
favorite = tweet['favorite_count']
retweet = tweet ['retweet_count']
id_status = tweet['id']
in_reply_to = tweet['in_reply_to_screen_name']
followers = tweet['user']['followers_count'] # nombre d'abonnés
statuses_count = tweet['user']['statuses_count'] # nombre d'abonnés
location = tweet['user']['location'] # résidence du twittos
tweet_text = tweet['text'].strip() # deux lignes enlèvent espaces inutiles
tweet_text = ''.join(tweet_text.splitlines())
print i,created_at,user_creation,user, tweet_text
if tweet['geo'] and tweet['geo']['coordinates'][0]:
lat, long = tweet['geo']['coordinates'][:2]
print u'#%s: %s' % (user, tweet_text), lat, long
else:
print u'#%s: %s' % (user, tweet_text)
print favorite,retweet,id_status,in_reply_to,followers,statuses_count,location
writer.writerow([user.encode('utf8'), user_creation.encode('utf8'), created_at.encode('utf8'),
tweet_text.encode('utf8'), favorite, retweet, id_status, in_reply_to, followers, statuses_count, location.encode('utf8'), lat, long])
i += 1
if i > max:
return()
Thank you in advance!
Florent
If EST is your local timezone then you could do it using only stdlib:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
timestamp = mktime_tz(parsedate_tz('Thu Mar 19 12:37:15 +0000 2015'))
s = str(datetime.fromtimestamp(timestamp))
# -> '2015-03-19 08:37:15'
It supports non-UTC input timezones too.
Or you could specify the destination timezone explicitly:
import pytz # $ pip install pytz
dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
s = dt.strftime('%Y-%m-%d %H:%M:%S')
# -> '2015-03-19 08:37:15'
You could put it in a function:
#!/usr/bin/env python
from datetime import datetime
from email.utils import parsedate_tz, mktime_tz
def to_local_time(tweet_time_string):
"""Convert rfc 5322 -like time string into a local time
string in rfc 3339 -like format.
"""
timestamp = mktime_tz(parsedate_tz(tweet_time_string))
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
time_string = to_local_time('Thu Mar 19 12:37:15 +0000 2015')
# use time_string here..
Remove the +0000 from the date sent by twitter and do something like:
from datetime import datetime
import pytz
local = 'Europe/London' #or the local from where twitter date is coming from
dt = datetime.strptime("Thu Mar 19 12:37:15 2015", "%a %b %d %H:%M:%S %Y")
dt = pytz.timezone(local).localize(dt)
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output:
2015-03-19 07:37:15
Alternatively you can do something like (in this case you don't need to remove the +0000 timezone info):
from dateutil import parser
dt = parser.parse("Thu Mar 19 12:37:15 +0000 2015")
est_dt = dt.astimezone(pytz.timezone('EST'))
print est_dt.strftime("%Y-%m-%d %H:%M:%S")
Output
2015-03-19 07:37:15
By the way, EST is UTC-4 or UTC-5?

Categories