i want to get the utc time directly from a website that can give that. and i don't want to use python modules because they give me the system time and my system time does not show the correct time.
how can i get the correct utc time without changing the system time?
i use
import ntplib,datetime
x = ntplib.NTPClient()
datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time)
but i get this error
raise NTPException("No response received from %s." % host)
ntplib.NTPException: No response received from europe.pool.ntp.org.
Could you try to call datetime.utcnow()? From the python docs
Here is my output
>>> import datetime
>>> datetime.datetime.utcnow()
datetime.datetime(2018, 11, 4, 9, 47, 59, 572104)
Edit as OP having issues with above
As for a web based solution, this works fine for me (Whilst avoiding your website
>>> import requests
>>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
>>> print(x.content)
b'abbreviation: GMT\ndatetime: 2018-11-04T10:09:18.395273+00:00\nday_of_week: 0\nday_of_year: 308\ndst: false\ndst_from: \ndst_until: \ntimezone: Europe/London\nunixtime: 1541326158\nutc_offset: +00:00\nweek_number: 44'
Update
You can get the datetime like so. I am certain there is a better way to do this, but this method works fine for this specific use-case.
>>> import requests
>>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
>>> y = x.text
>>> print(y[27:47])
2018-11-04T11:01:46
Related
New to python and I've been trying to create a program that returns the time a specific email was received and couldn't find a function anywhere that did so. (So far I've checked reddit, Stack Overflow and Automate the Boring stuff) I've been able to return the body of the email with the below but couldn't find anything on whether or not I can extract only the time from emails. Any help on if this is possible and how it can be done would be greatly appreciated.
Thanks
password = input('Enter your password')
import imapclient
server = imapclient.IMAPClient('imap-mail.outlook.com', ssl=True)
server.login('myemail#msn.com',password)
import pprint
pprint.pprint(server.list_folders())
server.select_folder('Inbox')
rawMessage = server.fetch(40111, ['BODY[]'])
import pyzmail
message = pyzmail.PyzMessage.factory(rawMessage[40111][b'BODY[]'])
messagebodyTEXT = message.text_part.get_payload().decode(message.text_part.charset)
print(messagebodyTEXT)
The library that you're using is talking the IMAP protocol. In IMAP, there's no such thing as a "time when a message was received". There's a timestamp on when that message was "stored into the mailbox (INTERNALDATE)", but that's a something else in the generic case.
You could also try to parse the Received headers which might (or might not) contain the information that you're looking for.
I see you're using the pyzmail third-party library, but did you know there's an extensive email module in the Python standard library?
Specifically I think the parser is what you'll want for extracting timestamps:
https://docs.python.org/3/library/email.parser.html
building on previous comments and answers regarding INTERNALDATE, here is the code snippet I used to retrieve the delivered date and transform it to a datetime object, with the imaplib library:
>>> import imaplib
>>> connection = imaplib.IMAP4_SSL('yourimapserver')
>>> response = connection.login('youremailaddress', 'password')
>>> connection.select('INBOX')
>>> status, data = connection.fetch(b'1', '(INTERNALDATE)') # b"1" is your uid
From there, different options depending on:
the format of the datetime your imap server provides,
whether you need a timezone aware object.
timezone naive
>>> import datetime
>>> import time
>>> data[0]
b'1 (INTERNALDATE "12-Aug-2020 16:38:19 +0200")'
>>> timestruct = imaplib.Internaldate2tuple(data[0])
>>> timestruct
time.struct_time(tm_year=2020, tm_mon=8, tm_mday=12,tm_hour=16, tm_min=38, tm_sec=19, tm_wday=2, tm_yday=225, tm_isdst=1)
>>> datetime_delivered = datetime.fromtimestamp(mktime(timestruct))
>>> datetime_delivered
datetime.datetime(2020, 8, 12, 16, 38, 19)
timezone aware (Python 3.2+)
>>> import email
>>> str_datetime = data[0].decode().split('"')[1]
>>> str_datetime
"12-Aug-2020 16:38:19 +0200"
>>> timezone_aware = email.utils.parsedate_to_datetime(str_datetime)
>>> timezone_aware
datetime.datetime(2020,8, 12, 16, 38, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))
I would like to be able to enter a server response code and have Requests tell me what the code means. For example, code 200 --> ok
I found a link to the source code which shows the dictionary structure of the codes and descriptions. I see that Requests will return a response code for a given description:
print requests.codes.processing # returns 102
print requests.codes.ok # returns 200
print requests.codes.not_found # returns 404
But not the other way around:
print requests.codes[200] # returns None
print requests.codes.viewkeys() # returns dict_keys([])
print requests.codes.keys() # returns []
I thought this would be a routine task, but cannot seem to find an answer to this in online searching, or in the documentation.
Alternatively, in case of Python 2.x, you can use httplib.responses:
>>> import httplib
>>> httplib.responses[200]
'OK'
>>> httplib.responses[404]
'Not Found'
In Python 3.x, use http module:
In [1]: from http.client import responses
In [2]: responses[200]
Out[2]: 'OK'
In [3]: responses[404]
Out[3]: 'Not Found'
One possibility:
>>> import requests
>>> requests.status_codes._codes[200]
('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '\xe2\x9c\x93')
The first value in the tuple is used as the conventional code key.
I had the same problem before and found the
answer in this question
Basically:
responsedata.status_code - gives you the integer status code
responsedata.reason - gives the text/string representation of the status code
requests.status_codes.codes.OK
works nicely and makes it more readable in my application code
Notice that in source code: the requests.status_codes.codes is of type LookupDict which overrides method getitem
You could see all the supported keys with - dir(requests.status_codes.codes)
When using in combination with FLASK:
i like use following enum from flask-api plugin
from flask_api import status where i get more descriptive version of HTTP status codes as in -
status.HTTP_200_OK
With Python 3.x this will work
>>> from http import HTTPStatus
>>> HTTPStatus(200).phrase
'OK'
I am trying to write a script to GET project data from Insightly and post to 10000ft. Essentially, I want to take any newly created project in one system and create that same instance in another system. Both have the concept of a 'Project'
I am extremely new at this but I only to GET certain Project parameters in Insightly to pass into the other system (PROJECT_NAME, LINKS:ORGANIZATION_ID, DATE_CREATED_UTC) to name a few.
I plan to add logic to only POST projects with a DATE_CREATED_UTC > yesterday, but I am clueless on how to setup the script to grab the JSON strings and create python variables (JSON datestring to datetime). Here is my current code. I am simply just printing out some of the variables I require to get comfortable with the code.
import urllib, urllib2, json, requests, pprint, dateutil
from dateutil import parser
import base64
#Set the 'Project' URL
insightly_url = 'https://api.insight.ly/v2.1/projects'
insightly_key =
api_auth = base64.b64encode(insightly_key)
headers = {
'GET': insightly_url,
'Authorization': 'Basic ' + api_auth
}
req = urllib2.Request(insightly_url, None, headers)
response = urllib2.urlopen(req).read()
data = json.loads(response)
for project in data:
project_date = project['DATE_CREATED_UTC']
project_name = project['PROJECT_NAME']
print project_name + " " + project_date
Any help would be appreciated
Edits:
I have updated the previous code with the following:
for project in data:
project_date = datetime.datetime.strptime(project['DATE_CREATED_UTC'], '%Y-%m-%d %H:%M:%S').date()
if project_date > (datetime.date.today() - datetime.timedelta(days=1)):
print project_date
else:
print 'No New Project'
This returns every project that was created after yesterday, but now I need to isolate these projects and post them to the other system
Here is an example of returning a datetime object from a parsed string. We will use the datetime.strptime method to accomplish this. Here is a list of the format codes you can use to create a format string.
>>> from datetime import datetime
>>> date_string = '2014-03-04 22:30:55'
>>> format = '%Y-%m-%d %H:%M:%S'
>>> datetime.strptime(date_string, format)
datetime.datetime(2014, 3, 4, 22, 30, 55)
As you can see, the datetime.strptime method returns a datetime object.
How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?
Use ntplib. Right from the manual:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
Just to save you some time. Here's the code I ended up with using phihag's answer. It prints the drift every interval_sec to screen and to a log file.
You'll need to easy_install ntplib for it to work.
import logging
logging.basicConfig(filename='time_shift.txt',level=logging.DEBUG)
import ntplib
import time
import datetime
c = ntplib.NTPClient()
interval_sec = 60
while True:
try:
response = c.request('europe.pool.ntp.org', version=3)
txt = '%s %.3f' % (datetime.datetime.now().isoformat(), response.offset)
print txt
logging.info(txt)
except:
pass
time.sleep(interval_sec)
Is there any facility in Django for doing currency conversions? Obviously, rates change day by day but I'm somewhat hopeful that the locale module has some sort of web-service based converter.
There's a snippet here that handles the formatting: http://www.djangosnippets.org/snippets/552/ But I need to localize the values first.
Probably more elegant ways to do this, but it works.
currency_in = 'USD'
currency_out = 'NOK'
import urllib2
req = urllib2.urlopen('http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='+currency_in+currency_out+'=X')
result = req.read()
# result = "USDNOK=X",5.9423,"5/3/2010","12:39pm"
Then you can split() the result for the modifier.
# Install google-currency package
# pip install google-currency
>>> from google_currency import convert
>>> convert('usd', 'bdt', 1)
Output:
{"from": "USD", "to": "BDT", "amount": "85.30", "converted": true}
You could use django-money app for currency conversions in Django-based projects.
It works with different rate sources and provides an interface to perform conversions & money localization:
>>> # After app setup & adding rates to the DB
>>> from djmoney.money import Money
>>> from djmoney.contrib.exchange.models import convert_money
>>> value = Money(100, 'EUR')
>>> converted = convert_money(value, 'USD')
>>> converted
<Money: 122.8184375038380800 USD>
>>> str(converted)
US$122.82
Formats are easily customizable, you could find the documentation on the project page.
You can use django-money to handle money values including the conversion of currencies as shown below. *The example below converts 100 USD to ... EUR:
# "views.py"
from django.http import HttpResponse
from app.models import MyModel
from djmoney.contrib.exchange.models import convert_money
from djmoney.money import Money
def test(request):
print(convert_money(Money(100, 'USD'), 'EUR')) # Here
return HttpResponse("Test")
You can see my answer and django-money doc which explain more about how to convert currencies.