Wednesday, March 27, 2013

python - current date and time example

Here's a code example showing how to create date & time strings.

# first, we need to import the datetime module
# in order to use date & time functions.
import datetime

# create and print string example #1
timestring = datetime.datetime.now().strftime("%Y-%m-%d-%H%M")
print(timestring)

# create and print string example #2
timestring = datetime.datetime.now().strftime("%Y-%m")
print(timestring)

# append a text to the end of string example #2
timestring = timestring + "-logfile.txt"
print(timestring)

Here's what the output will look like:

2013-03-27-1449
2013-03
2013-03-logfile.txt


More info on how to format the datetime string can be found here.

Hope this helps you!

No comments:

Post a Comment