format a date in to the format october 13, 2014 11:13:00.000 am gmt-07:00 in python

You can format a date in the given format using the datetime.strftime method and the pytz library for timezone support. Here is an example code snippet:

main.py
import datetime
import pytz

# create a datetime object representing the given date and time in UTC
dt_utc = datetime.datetime(2014, 10, 13, 18, 23, 0, 0, tzinfo=pytz.utc)

# convert to the desired timezone (GMT-7 in this example) and format the date string
dt_local = dt_utc.astimezone(pytz.timezone('America/Los_Angeles'))
date_str = dt_local.strftime('%B %d, %Y %I:%M:%S.%f %p %Z%z')

print(date_str)  # October 13, 2014 11:13:00.000 AM PDT-0700
449 chars
12 lines

Note that the strftime format string specifies the desired output format as follows:

  • %B: full month name (e.g. "October")
  • %d: day of the month (e.g. "13")
  • %Y: year (e.g. "2014")
  • %I: 12-hour format hour (e.g. "11")
  • %M: minute (e.g. "13")
  • %S: second (e.g. "00")
  • %f: microsecond (e.g. "000000")
  • %p: AM or PM
  • %Z: timezone abbreviation (e.g. "PDT")
  • %z: timezone offset from UTC (e.g. "-0700")

gistlibby LogSnag