Tag Archives: Python

Python – Convert a timezone aware datetime to UTC datetime using pytz

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

Advertisement

Python – Specify datetime timezone 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

Python – Create current datetime object with timezone

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

Python – Open URL with HTTP Authentication using 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

Django – Sort the Djano Admin list table by specific field

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

Django – Automatic creation date and update date

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