How can I create basic timestamps or dates? (Python 3.4)

DatetimePython 3.xDatetime Format

Datetime Problem Overview


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?

Datetime Solutions


Solution 1 - Datetime

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

Solution 2 - Datetime

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Solution 3 - Datetime

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZach ReneauView Question on Stackoverflow
Solution 1 - DatetimeZach ReneauView Answer on Stackoverflow
Solution 2 - DatetimeVlad BezdenView Answer on Stackoverflow
Solution 3 - DatetimeShubh PatelView Answer on Stackoverflow