Feb. 17, 2013

Date and Time Script

Overview

This script can be used to parse date and time. 

Open a blank file and name it for example dateParser.py 

Copy and paste the code below (and make sure you understand what it does) into
the file.

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 parenthesis.
# 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

I found this date and time script on this excellent website:
http://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
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:
Current year: 2013
Current month: 2
Current day: 17
Current hour: 16
Current minute: 2
Current second: 49
Current microsecond: 338517

Current date and time using strftime:
2013-02-17 16:02

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.