pretty

Tuesday, October 30, 2012

Adding or subtracting a date in python

Some examples for calculating dates in the past and future.

import datetime
"""
use timedelta for rolling dates
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,
hours=0, weeks=0)
"""
a_week_ago = datetime.datetime.now() - datetime.timedelta(weeks=1)
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
print a_week_ago
#2012-10-23 21:58:00.109116
print tomorrow
#2012-10-31
#and so on . . .
more here
and here

Python datetime to unix timestamp

The most simple solution for converting datetime to unix timestamp


import datetime
import time
import calendar

#Returns string
d = datetime.datetime.now()
d.strftime('%s')

#another solution returns int
calendar.timegm(d.timetuple())

#Yet another solution, returns float
time.mktime(d.timetuple())

Monday, October 15, 2012

Sanitize tshark date

A script to format date from tshark in a customizable way.
usage


tshark -tad -r example.pcap -T fields -e frame.time_epoch -e ip.src -e ip.dst | ./epochtodate.py


2009-12-16 12:25:37 570704 10.0.2.15 224.0.0.251
2009-12-16 12:25:38 802853 10.0.2.15 194.179.1.100
2009-12-16 12:25:43 808373 10.0.2.15 62.14.2.1
2009-12-16 12:25:43 976156 62.14.2.1 10.0.2.15
2009-12-16 12:25:43 979653 10.0.2.15 194.179.1.100
2009-12-16 12:25:48 983549 10.0.2.15 62.14.2.1
2009-12-16 12:25:49 148470 62.14.2.1 10.0.2.15
2009-12-16 12:25:49 148789 10.0.2.15 194.179.1.100
2009-12-16 12:25:49 228531 194.179.1.100 10.0.2.15



#!/usr/bin/python
'''
Convert tshark frame.time_epoch to readable date
'''
import datetime
import fileinput
import re

def epochtodate(line):
re_epoch = re.compile("([0-9]{10}\.[0-9]{9})")
found = re_epoch.search(line)

if found:
nowstring = datetime.datetime.fromtimestamp(float(found.group(1))).strftime('%Y-%m-%d %H:%M:%S %f')
line = re.sub("[0-9]{10}\.[0-9]{9}",nowstring,line)
print line.rstrip("\n")
else:
print line

for line in fileinput.input():
epochtodate(line)

Thursday, October 4, 2012

Sort a dictionary in python

Sort by value

http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value

import operator
x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
If you want to have descending just add reverse=True

sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)

Sort by key

http://stackoverflow.com/questions/9001509/python-dictionary-sort-by-key

import collections

d = {2:3, 1:89, 4:5, 3:0}
od = collections.OrderedDict(sorted(d.items()))