57

As a beginner, creating timestamps or formatted dates ended up being a little more of a challenge than I would have expected. What are some basic examples for reference?

Zach Reneau
  • 1,893
  • 2
  • 15
  • 13

4 Answers4

118

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

Zach Reneau
  • 1,893
  • 2
  • 15
  • 13
23
>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
2
from datetime import datetime

dt = datetime.now()    # for date and time
ts = datetime.timestamp(dt)    # for timestamp

print("Date and time is:", dt)
print("Timestamp is:", ts)
Shubh Patel
  • 87
  • 1
  • 6
2

You might want to check string to datetime operations for formatting.

from datetime import datetime

datetime_str = '09/19/18 13:55:26'

datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')

print(type(datetime_object))
print(datetime_object)  # printed in default format

Output:

<class 'datetime.datetime'>

2018-09-19 13:55:26