SaltyCrane: datetimehttps://www.saltycrane.com/blog/2010-10-16T00:04:22-07:00How to get the date N days ago in Python
2010-10-16T00:04:22-07:00https://www.saltycrane.com/blog/2010/10/how-get-date-n-days-ago-python/<pre class="python">from datetime import datetime, timedelta
N = 2
date_N_days_ago = datetime.now() - timedelta(days=N)
print(datetime.now())
print(date_N_days_ago)</pre>
<p>Results:</p>
<pre class="console">2019-03-01 13:02:15.056303
2019-02-27 13:02:15.056285</pre>
<p>
For more information see the <a href="https://docs.python.org/3/library/datetime.html#timedelta-objects">
timedelta documentation
</a>
</p>
Converting time zones for datetime objects in Python
2009-05-05T20:25:20-07:00https://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/<h4 id="install-pytz">Install pytz</h4>
<p>I am using <a href="http://pytz.sourceforge.net/">pytz</a>, which is
a time zone definitions package. You can install it using Easy Install.
On Ubuntu, do this:</p>
<pre>sudo easy_install --upgrade pytz</pre>
<h4 id="add-timezone">Add time zone information to a naive datetime object</h4>
<pre class="python">from datetime import datetime
from pytz import timezone
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC'))
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")</pre>
<p>Results:</p>
<pre>2009-05-05 22:28:15 UTC+0000</pre>
<h4 id="add-timezone-localize">Add non-UTC time zone information to a naive datetime object</h4> <em>(Added 2014-05-28)</em>
<p>NOTE: <code>datetime.replace()</code> does not handle daylight savings time
correctly. The correct way is to use <code>timezone.localize()</code> instead.
Using <code>datetime.replace()</code> is OK when working with UTC as shown above
because it does not have daylight savings time transitions to deal with.
See the <a href="http://pytz.sourceforge.net/">pytz documentation</a>.
</p>
<pre class="python">from datetime import datetime
from pytz import timezone
date_str = "2014-05-28 22:28:15"
datetime_obj_naive = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
# Wrong way!
datetime_obj_pacific = datetime_obj_naive.replace(tzinfo=timezone('US/Pacific'))
print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")
# Right way!
datetime_obj_pacific = timezone('US/Pacific').localize(datetime_obj_naive)
print datetime_obj_pacific.strftime("%Y-%m-%d %H:%M:%S %Z%z")</pre>
<p>Results:</p>
<pre>2014-05-28 22:28:15 PST-0800
2014-05-28 22:28:15 PDT-0700</pre>
<h4 id="convert-timezones">Convert time zones</h4>
<pre class="python">from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(fmt)
# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)
# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)</pre>
<p>Results:</p>
<pre>2009-05-06 03:09:49 UTC+0000
2009-05-05 20:09:49 PDT-0700
2009-05-06 05:09:49 CEST+0200</pre>
<h4 id="list-timezones">List time zones</h4>
<p>There are 559 time zones included in pytz. Here's how to print the
US time zones:</p>
<pre class="python">from pytz import all_timezones
print len(all_timezones)
for zone in all_timezones:
if 'US' in zone:
print zone</pre>
<p>Results:</p>
<pre>US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Pacific-New
US/Samoa</pre>
<h4 id="see-also">See also:</h4>
<ul>
<li><a href="http://docs.python.org/library/datetime.html">
http://docs.python.org/library/datetime.html</a> - Python datetime module documentation
</li>
<li><a href="http://uswaretech.com/blog/2009/02/understanding-datetime-tzinfo-timedelta-timezone-conversions-python/">
http://uswaretech.com/blog/2009/02/understanding-datetime-tzinfo-timedelta-timezone-conversions-python/</a>
- More info on tzinfo and datetime objects.
</li>
</ul>
Python datetime / time conversions
2008-11-12T16:45:42-08:00https://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/<pre class="python">from datetime import datetime
import time
#-------------------------------------------------
# conversions to strings
#-------------------------------------------------
# datetime object to string
dt_obj = datetime(2008, 11, 10, 17, 53, 59)
date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
print date_str
# time tuple to string
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print date_str
#-------------------------------------------------
# conversions to datetime objects
#-------------------------------------------------
# time tuple to datetime object
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
dt_obj = datetime(*time_tuple[0:6])
print repr(dt_obj)
# date string to datetime object
date_str = "2008-11-10 17:53:59"
dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(dt_obj)
# timestamp to datetime object in local time
timestamp = 1226527167.595983
dt_obj = datetime.fromtimestamp(timestamp)
print repr(dt_obj)
# timestamp to datetime object in UTC
timestamp = 1226527167.595983
dt_obj = datetime.utcfromtimestamp(timestamp)
print repr(dt_obj)
#-------------------------------------------------
# conversions to time tuples
#-------------------------------------------------
# datetime object to time tuple
dt_obj = datetime(2008, 11, 10, 17, 53, 59)
time_tuple = dt_obj.timetuple()
print repr(time_tuple)
# string to time tuple
date_str = "2008-11-10 17:53:59"
time_tuple = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(time_tuple)
# timestamp to time tuple in UTC
timestamp = 1226527167.595983
time_tuple = time.gmtime(timestamp)
print repr(time_tuple)
# timestamp to time tuple in local time
timestamp = 1226527167.595983
time_tuple = time.localtime(timestamp)
print repr(time_tuple)
#-------------------------------------------------
# conversions to timestamps
#-------------------------------------------------
# time tuple in local time to timestamp
time_tuple = (2008, 11, 12, 13, 59, 27, 2, 317, 0)
timestamp = time.mktime(time_tuple)
print repr(timestamp)
# time tuple in utc time to timestamp
time_tuple_utc = (2008, 11, 12, 13, 59, 27, 2, 317, 0)
timestamp_utc = calendar.timegm(time_tuple_utc)
print repr(timestamp_utc)
#-------------------------------------------------
# results
#-------------------------------------------------
# 2008-11-10 17:53:59
# 2008-11-12 13:51:18
# datetime.datetime(2008, 11, 12, 13, 51, 18)
# datetime.datetime(2008, 11, 10, 17, 53, 59)
# datetime.datetime(2008, 11, 12, 13, 59, 27, 595983)
# datetime.datetime(2008, 11, 12, 21, 59, 27, 595983)
# (2008, 11, 10, 17, 53, 59, 0, 315, -1)
# (2008, 11, 10, 17, 53, 59, 0, 315, -1)
# (2008, 11, 12, 21, 59, 27, 2, 317, 0)
# (2008, 11, 12, 13, 59, 27, 2, 317, 0)
# 1226527167.0
# 1226498367</pre>
How to get the current date and time in Python
2008-06-26T13:06:00-07:00https://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/<p>Here is an example of how to get the current date and time using the <code>datetime</code>
module in Python:</p>
<pre class="python">import datetime
now = datetime.datetime.now()
print
print "Current date and time using str method of datetime object:"
print str(now)
print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")
print
print "Current date and time using isoformat:"
print now.isoformat()</pre>
<br />Results:<br />
<pre>Current date and time using str method of datetime object:
2014-09-26 16:34:40.278298
Current date and time using instance attributes:
Current year: 2014
Current month: 9
Current day: 26
Current hour: 16
Current minute: 34
Current second: 40
Current microsecond: 278298
Current date and time using strftime:
2014-09-26 16:34
Current date and time using isoformat:
2014-09-26T16:34:40.278298</pre>
<br />
<p>Directly from the
<a href="http://docs.python.org/library/time.html#time.strftime">
<code>time</code> module documentation</a>, here are more options to use with
<code>strftime</code>:</p>
<table>
<thead>
<tr>
<th class="center">Directive</th>
<th class="left">Meaning</th>
<th class="center">Notes</th>
</tr>
</thead>
<tbody>
<tr><td class="center" valign="baseline"><code>%a</code></td>
<td class="left">Locale's abbreviated weekday name.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%A</code></td>
<td class="left">Locale's full weekday name.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%b</code></td>
<td class="left">Locale's abbreviated month name.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%B</code></td>
<td class="left">Locale's full month name.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%c</code></td>
<td class="left">Locale's appropriate date and time representation.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%d</code></td>
<td class="left">Day of the month as a decimal number [01,31].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%H</code></td>
<td class="left">Hour (24-hour clock) as a decimal number [00,23].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%I</code></td>
<td class="left">Hour (12-hour clock) as a decimal number [01,12].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%j</code></td>
<td class="left">Day of the year as a decimal number [001,366].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%m</code></td>
<td class="left">Month as a decimal number [01,12].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%M</code></td>
<td class="left">Minute as a decimal number [00,59].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%p</code></td>
<td class="left">Locale's equivalent of either AM or PM.</td>
<td class="center">(1)</td></tr>
<tr><td class="center" valign="baseline"><code>%S</code></td>
<td class="left">Second as a decimal number [00,61].</td>
<td class="center">(2)</td></tr>
<tr><td class="center" valign="baseline"><code>%U</code></td>
<td class="left">Week number of the year (Sunday as the first day of the
week) as a decimal number [00,53]. All days in a new year
preceding the first Sunday are considered to be in week 0.</td>
<td class="center">(3)</td></tr>
<tr><td class="center" valign="baseline"><code>%w</code></td>
<td class="left">Weekday as a decimal number [0(Sunday),6].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%W</code></td>
<td class="left">Week number of the year (Monday as the first day of the
week) as a decimal number [00,53]. All days in a new year
preceding the first Monday are considered to be in week 0.</td>
<td class="center">(3)</td></tr>
<tr><td class="center" valign="baseline"><code>%x</code></td>
<td class="left">Locale's appropriate date representation.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%X</code></td>
<td class="left">Locale's appropriate time representation.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%y</code></td>
<td class="left">Year without century as a decimal number [00,99].</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%Y</code></td>
<td class="left">Year with century as a decimal number.</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%Z</code></td>
<td class="left">Time zone name (no characters if no time zone exists).</td>
<td class="center"></td></tr>
<tr><td class="center" valign="baseline"><code>%%</code></td>
<td class="left">A literal "<tt class="character">%</tt>" character.</td>
<td class="center"></td></tr></tbody>
</table>
<br /><br />See also:<br />
<ul>
<li><a href="http://docs.python.org/library/datetime.html#datetime-datetime">
<code>datetime</code> Objects</a> in the
<a href="http://docs.python.org/library/datetime.html">
<code>datetime</code> module</a> of the
<a href="http://docs.python.org/library/index.html">
Python Library Reference</a>.</li>
</ul>