Build a Date and Time Script in Python

Date and Time Script in Python

Build a Date and Time Script in Python


Build a Date and Time Script in Python:

This script can be used to parse date and time. Open a blank file and name it for example dateParser.py.

dateParser.py:

from datetime import datetime
now = datetime.now()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss

Now save and exit the file and run it by:

$ python dateParser.py

Time.sleep:

In Python you can use time.sleep() to suspend execution for the given number of seconds. The seconds are being given between the parentheses.

# How to sleep for 5 seconds in python:
import time
time.sleep(5)
# How to sleep for 0.5 seconds in python:
import time
time.sleep(0.5)

How to get the current date and time:

import datetime
now = datetime.datetime.now()
print
print "Current date and time using str method of datetime object:"
print str(now)
print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")

The result:

Current date and time using str method of datetime object:

2013-02-17 16:02:49.338517

Current date and time using instance attributes:

Year Month Day House Minute Second Microsecond
2013 2 17 16 2 49 338517

Current date and time using strftime:

2013-02-17 16:02

Conclusion:

I hope this quick guide helps you on your way.  We all have to start somewhere and for me a simple script like this can be the gateway to something much greater.

Thank you



Leave a Reply