Previously:
If we have a datetime with timezone , we can also convert it to UTC datetime using pytz .
import pytz
import datetime
local_tz = pytz.timezone ("Asia/Hong_Kong")
datetime_without_tz = datetime.datetime.strptime("2015-02-14 12:34:56", "%Y-%m-%d %H:%M:%S")
datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=None) # No daylight saving time
datetime_in_utc = datetime_with_tz.astimezone(pytz.utc)
str1 = datetime_without_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str2 = datetime_with_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str3 = datetime_in_utc.strftime('%Y-%m-%d %H:%M:%S %Z')
print 'Without Timzone : %s' % (str1)
print 'With Timezone : %s' % (str2)
print 'UTC Datetime : %s' % (str3)
Continue reading Python – Convert a timezone aware datetime to UTC datetime using pytz →
We can use the dateutil package to create timezone aware datetime .
We can also use the pytz to specify the timezone . Try the following example.
import pytz
import datetime
local_tz = pytz.timezone ("Asia/Hong_Kong")
datetime_without_tz = datetime.datetime.strptime("2015-02-14 12:34:56", "%Y-%m-%d %H:%M:%S")
datetime_with_tz = local_tz.localize(datetime_without_tz, is_dst=None) # No daylight saving time
str1 = datetime_without_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str2 = datetime_with_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
print 'Without Timzone : %s' % (str1)
print 'With Timezone : %s' % (str2)
Continue reading Python – Specify datetime timezone using pytz →
Handling timezone is quite a pain in Python . When you create or read a datetime object, you need to make sure whether the datetime you need should be timezone aware or not.
Here is a simple example to create a datetime with timezone . The tzlocal will determine the timezone setting of the operating system and apply it to your datetime object.
import datetime
from dateutil.tz import tzlocal
now_without_tz = datetime.datetime.now()
now_with_tz = datetime.datetime.now(tzlocal())
str1 = now_without_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
str2 = now_with_tz.strftime('%Y-%m-%d %H:%M:%S %Z')
print 'Without Timzone : %s' % (str1)
print 'With Timezone : %s' % (str2)
Continue reading Python – Create current datetime object with timezone →
Let’s continue our example in
So now we have a working endpoint @ h ttp://127.0.0.1:8000/custom/get/ .
Continue reading Django REST framework – Setting permissions →
We can set the proxy before making request using urllib2 .
proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')
&nvbsp;
Done =)
Reference: StackOverflow – Proxy with urllib2
Here is an example Python program to read a JSON via URL using urllib2 and simplejson .
import urllib2
import simplejson
response = urllib2.urlopen("http://172.0.0.1:8000/custom/get/")
data = simplejson.load(response)
print data
# => {'content': 'Hello World!', 'success': True}
Continue reading Python – Read and parse a JSON via URL →
The urllib2 package allows us to override the host table before we make request. Here is an example which will map www .google.com to my local machine.
Continue reading Python – Custom host mapping in urllib2 →
Update @ 2015-04-01: Mart suggests using the Requests package. =)
We could add HTTP authentication credential when opening and URL using urllib2 .
import urllib2
import base64
import simplejson
username = "<username>"
password = "<password>"
request = urllib2.Request("http://127.0.0.1:8000/custom/get/")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
data = simplejson.load(response)
print data
Done =)
Reference: StackOverflow – Python urllib2 Basic Auth Problem
We could display our model objects on the Django Admin .
The list table could be sorted by specific column. Say we have added the creation date to the Person model class.
models.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=256)
homepage = models.URLField(max_length=256)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
Continue reading Django – Sort the Djano Admin list table by specific field →
In your model class, we can set the auto_now_add and auto_add in the DateField or DateTimeField for creation date and update date.
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=256)
homepage = models.URLField(max_length=256)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
The auto_now_add will make the field read only while the auto_now will refresh the the field value when a .save() is executed.
Done =)
Reference: Django documentation – DateField
Posts navigation
Dream BIG and go for it =)