Home > python > Current date and time

Current date and time

#!/usr/bin/env python

from datetime import datetime

now = datetime.now()
date = datetime.date(now)
time = datetime.time(now)
print "%d-%02d-%02d @ %02dh%02d" % (date.year, date.month, date.day, time.hour, time.minute)

Sample output:

2011-02-25 @ 11h23

Update (20110523)
I wanted to use a timestamp in the name of a temporary file. Here is a slightly modified version of the code above:

print "{year}{month:02}{day:02}_{hour:02}{minute:02}{second:02}".format(year=date.year, month=date.month, day=date.day, hour=time.hour, minute=time.minute, second=time.second)

Sample output:

Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: