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.
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
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")
Current date and time using str method of datetime object:
Current date and time using instance attributes:
Current date and time using strftime:
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.