Python datetime formatting using time, calendar and datetime


Python date/time formatting example;

#Created on Jul 25, 2013

#@author: tunatore

import time;
import calendar;
from datetime import date;

currenTimeTuple = time.localtime(time.time())
print ("current timeTuple :", currenTimeTuple)

#accessing tuple values
print ("current year:", currenTimeTuple[0])
print ("current month:", currenTimeTuple[1])
print ("current day:", currenTimeTuple[2])

print ("current hour:", currenTimeTuple[3])
print ("current minute:", currenTimeTuple[4])
print ("current second:", currenTimeTuple[5])

print ("\n")
#getting calendar
calenderTxt = calendar.month(2013,7)
print (calenderTxt)

#formatted times
print (time.asctime(currenTimeTuple))
print (time.strftime("%Y-%m-%d %H:%M:%S", currenTimeTuple))
print (time.strftime("%d-%m-%Y %H:%M:%S", currenTimeTuple))

#current date formatted
nowDate = date.fromtimestamp(time.time())

#ISO format current
print ("Now" , nowDate.isoformat())
print ("Now Custom Format", nowDate.strftime("%d/%m/%y"))

output;

current timeTuple : time.struct_time(tm_year=2013, tm_mon=7, tm_mday=25, tm_hour=18, tm_min=12, tm_sec=19, tm_wday=3, tm_yday=206, tm_isdst=1)
current year: 2013
current month: 7
current day: 25
current hour: 18
current minute: 12
current second: 19

July 2013
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Thu Jul 25 18:12:19 2013
2013-07-25 18:12:19
25-07-2013 18:12:19
Now 2013-07-25
Now Custom Format 25/07/13

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s