Convert Facebook Event start/end times to UTC - python

I'm having trouble getting event start in end times in UTC format from facebook.
I'm using the Facebook Python library, I am running these queries to retrieve events:
fb_events = graph.get_connections(fb_user["id"], "events", args=["date_format=U"])
for item in fb_events['data']:
curr_event = graph.get_object(item['id'], args=["date_format=U"])
The last line of the code is where I actually get the event containing the start and end times. The arg: "date_format=U" is supposed to specify the time format in unix time, which is already in UTC, however, this code still returns normal Facebook time stamps, in local time.
How can I get this information in UTC time, or in some sort of time that is consistent across time zones?
Thanks!

The following might help you to do the conversion:
import pytz, datetime, time
import os
originalTimeStamp = os.stat("/tmp/file-from-us-west-coast").st_mtime
# prints e.g. 2010-03-31 13:01:18
print "original:",datetime.datetime.fromtimestamp(originalTimeStamp)
# re-interpret
originalTimeZone = "America/Los_Angeles"
targetTimeZone = "Europe/Paris"
newTimeStamp = pytz.timezone(originalTimeZone).localize(datetime.datetime.fromtimestamp(originalTimeStamp)).astimezone(pytz.timezone(targetTimeZone))
# prints e.g. 2010-03-31 22:01:18+02:00
print "new: ",newTimeStamp
# convert back to seconds since epoch
newTimeStamp = time.mktime(newTimeStamp.timetuple())
# print time difference in hours
print (newTimeStamp - originalTimeStamp) / 3600.0
See this link for more information: http://pytz.sourceforge.net/
Another example of the code
from datetime import *
from pytz import timezone
import pytz
[...]
if (not isinstance(pacificTime, int)):
pacificTime = int(pacificTime)
originalTimeZone = "America/Los_Angeles"
print datetime.fromtimestamp(pacificTime, pytz.timezone(originalTimeZone))

Related

How to take time as a input from user in the form HHMM and then run a function at that time

I am writing a code where the user will be asked for time in the form of HHMM multiple times using a loop and then this time will be appended to a list. Now I want a function to be executed at the various times in that list provided by the user.
You can use datetime to perform the necessary calculations.
In this example, the target time is parsed using strptime but the date is not supplied so the time part is correct but the date part is wrong. The first three fields (year, month, day) are then replaced with today's date to produce a datetime object that correctly represents the target time. The current time can then be subtracted to give a timedelta object that represents the amount of time that needs to be waited until the task can be run.
import time
import datetime
def hello():
print("hello")
def run_at_times(func, times):
today = datetime.date.today()
for hhmm in sorted(times):
dt = datetime.datetime.strptime(hhmm, "%H%M")
when = datetime.datetime(*today.timetuple()[:3],
*dt.timetuple()[3:6])
wait_time = (when - datetime.datetime.now()).total_seconds()
if wait_time < 0:
print(f'Time {when} has already passed')
else:
print(f'Waiting {wait_time} seconds until {when}')
time.sleep(wait_time)
func()
run_at_times(hello, ["1041", "1203", "1420"])

Need to check current time from NTP server is within some time range in python

I need to check if current time from NTP server (using ntplib module) is within some required time range.
I have written the below code but I need some help to finish this task.
#!/usr/bin/python
import ntplib
from time import ctime
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org')
print (ctime(response.tx_time))
Output:
Fri Aug 16 13:26:16 2019
Now I need to check the ntp current time "13:26:16" is within the time range "09:30:00 - 15:30:00", so how can we check this in Python?
It must say current ntp time is/not in time range "09:30:00 - 15:30:00"
Convert the epoch timestamp to a suitable representation such as a Python datetime object and inspect the hours and minutes fields.
from time import gmtime
# ...
dt = time.gmtime(response.tx_time)
if (dt.tm_hour == 9 and dt.tm_min >= 30) or (
10 <= dt.tm_hour <= 14) or (
dt.tm_hour == 15 and dt.tm_min <= 30):
print('yes indeed')
else:
print('not')
Time zones are always tricky; the above gets you UTC (as vaguely implied by the name gmtime). If you want to compare to the value in your local time zone, try time.localtime instead.

Moved time zones now datetime.utcnow() is incorrect

I'm working on a Python application that fires notifications at certain times. I started working on this project in Italy and the program worked fine, but now that I'm back in the U.S., the time is completely wrong. There's a four hour time difference between the actual time and the time that is shown, which is weird, because Italy is 6 hours ahead.
For example, the time that datetime.utcnow() shows is 2016-05-10T18:55:47.920001Z but the time is actually 2016-05-10T14:55:47.920001Z
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
I tried using pytz to set the time zone (which gives me the correct time), but the API that I'm sending the current time to (Google Calendar), won't accept it. This time isn't accepted but the line of code above is, but the time is wrong.
eastern = pytz.timezone("America/New_York")
now = datetime.datetime.now(tz=eastern).isoformat() + 'Z' # 'Z' indicates UTC time
How can I get datetime.datetime.utcnow() to reflect my current time?
.utcnow() returns time in UTC. It returns the exact same value wherever you are. UTC time is the same in Italy and in US.
To generate rfc3339 timestamp: .utcnow().isoformat() + 'Z' is correct.
datetime.now(eastern).isoformat() + 'Z' is wrong. Use just datetime.now(eastern).isoformat():
>>> from datetime import datetime
>>> import pytz
>>> eastern = pytz.timezone('America/New_York')
>>> datetime.utcnow().isoformat()+'Z', datetime.now(eastern).isoformat()
('2016-05-11T15:25:18.857833Z', '2016-05-11T11:25:18.857860-04:00')
Both return the same time (if we ignore microseconds). Today, 15:25UTC is the same time as 11:25 in New York:
<local time> == <utc time> + <utc offset>
11:25 == 15:25 + (-04:00)
Try:
from datetime import datetime, timezone
# 'Z' indicates UTC time
now = datetime.now(timezone.utc).astimezone().isoformat() + 'Z'
print(now)

Convert localtime to unix timestamp [duplicate]

I have strings in YMD hms format that had the timezone stripped. But I know they are in Eastern time with daylight savings time.
I am trying to convert them into epoch timestamps for UTC time.
I wrote the following function:
def ymdhms_timezone_dst_to_epoch(input_str, tz="US/Eastern"):
print(input_str)
dt = datetime.datetime.fromtimestamp(time.mktime(time.strptime(input_str,'%Y-%m-%d %H:%M:%S')))
local_dt = pytz.timezone(tz).localize(dt)
print(local_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
utc_dt = local_dt.astimezone(pytz.utc)
print(utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
e = int(utc_dt.strftime("%s"))
print(e)
return e
Given string `2015-04-20 21:12:07` this prints:
2015-04-20 21:12:07
2015-04-20 21:12:07 EDT-0400 #<- so far so good?
2015-04-21 01:12:07 UTC+0000 #<- so far so good?
1429596727
which looks ok up to the epoch timestamp. But http://www.epochconverter.com/epoch/timezones.php?epoch=1429596727 says it should mao to
Greenwich Mean Time Apr 21 2015 06:12:07 UTC.
What is wrong?
I have strings in YMD hms format that had the timezone stripped. But I know they are in Eastern time with daylight savings time.
A portable way is to use pytz:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
naive_dt = datetime.strptime('2015-04-20 21:12:07', '%Y-%m-%d %H:%M:%S')
tz = pytz.timezone('US/Eastern')
eastern_dt = tz.normalize(tz.localize(naive_dt))
print(eastern_dt)
# -> 2015-04-20 21:12:07-04:00
I am trying to convert them into epoch timestamps for UTC time.
timestamp = (eastern_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
# -> 1429578727.0
See Converting datetime.date to UTC timestamp in Python.
There are multiple issues in your code:
time.mktime() may return a wrong result for ambiguous input time (50% chance) e.g., during "fall back" DST transition in the Fall
time.mktime() and datetime.fromtimestamp() may fail for past/future dates if they have no access to a historical timezone database on a system (notably, Windows)
localize(dt) may return a wrong result for ambiguous or non-existent time i.e., during DST transitions. If you know that the time corresponds to the summer time then use is_dst=True. tz.normalize() is necessary here, to adjust possible non-existing times in the input
utc_dt.strftime("%s") is not portable and it does not respect tzinfo object. It interprets input as a local time i.e., it returns a wrong result unless your local timezone is UTC.
Can I just always set is_dst=True?
You can, if you don't mind getting imprecise results for ambiguous or non-existent times e.g., there is DST transition in the Fall in America/New_York time zone:
>>> from datetime import datetime
>>> import pytz # $ pip install pytz
>>> tz = pytz.timezone('America/New_York')
>>> ambiguous_time = datetime(2015, 11, 1, 1, 30)
>>> time_fmt = '%Y-%m-%d %H:%M:%S%z (%Z)'
>>> tz.localize(ambiguous_time).strftime(time_fmt)
'2015-11-01 01:30:00-0500 (EST)'
>>> tz.localize(ambiguous_time, is_dst=False).strftime(time_fmt) # same
'2015-11-01 01:30:00-0500 (EST)'
>>> tz.localize(ambiguous_time, is_dst=True).strftime(time_fmt) # different
'2015-11-01 01:30:00-0400 (EDT)'
>>> tz.localize(ambiguous_time, is_dst=None).strftime(time_fmt)
Traceback (most recent call last):
...
pytz.exceptions.AmbiguousTimeError: 2015-11-01 01:30:00
The clocks are turned back at 2a.m. on the first Sunday in November:
is_dst disambiguation flag may have three values:
False -- default, assume the winter time
True -- assume the summer time
None -- raise an exception for ambiguous/non-existent times.
is_dst value is ignored for existing unique local times.
Here's a plot from PEP 0495 -- Local Time Disambiguation that illustrates the DST transition:
The local time repeats itself twice in the fold (summer time -- before the fold, winter time -- after).
To be able to disambiguate the local time automatically, you need some additional info e.g., if you read a series of local times then it may help if you know that they are sorted: Parsing of Ordered Timestamps in Local Time (to UTC) While Observing Daylight Saving Time.
First of all '%s' is not supported on all platforms , its actually working for you because your platform C library’s strftime() function (that is called by Python) supports it. This function is what is causing the issue most probably, I am guessing its not timezone aware , hence when taking difference from epoch time it is using your local timezone, which is most probably EST(?)
Instead of relying on '%s' , which only works in few platforms (linux, I believe) , you should manually subtract the datetime you got from epoch (1970/1/1 00:00:00) to get the actual seconds since epoch . Example -
e = (utc_dt - datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.utc)).total_seconds()
Demo -
>>> (utc_dt - datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.utc)).total_seconds()
1429578727.0
This correctly corresponds to the date-time you get.
I don't exactly know why but you have to remove the timezone info from your utc_dt before using %s to print it.
e = int(utc_dt.replace(tzinfo=None).strftime("%s"))
print(e)
return e

Getting Python to Print the Hour of Day

I am using the following code to get the time:
import time
time = time.asctime()
print(time)
I end up with the following result:
'Tue Feb 25 12:09:09 2014'
How can I get Python to print just the hour?
You can use datetime:
>>> import datetime as dt
>>> dt.datetime.now().hour
9
Or, rather than now() you can use today():
>>> dt.datetime.today().hour
9
Then insert into any string desired:
>>> print('The hour is {} o\'clock'.format(dt.datetime.today().hour))
The hour is 9 o'clock
Note that datetime.today() and datetime.now() are both using your computer's notion of local time zone (ie, a 'naive' datetime object).
If you want to use time zone info, it is not so trivial. You can either be on Python 3.2+ and use datetime.timezone or use the third party pytz. I am assuming your computer's timezone is fine, and a naive (non time zone datetime object) is fairly easy to use.
import time
print (time.strftime("%H"))
time.asctime() will create a string, so extracting the hours part is hard. Instead, get a proper time.struct_time object, which exposes the components directly:
t = time.localtime() # gives you an actual struct_time object
h = t.tm_hour # gives you the hour part as an integer
print(h)
You can do it in one step if that's all you need the hour for:
print(time.localtime().tm_hour)

Categories

Resources