Python/Datetime: Difference between revisions

From Fundamental Ramen
Jump to navigation Jump to search
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Parse =
= Parsing =
{| class="wikitable"
{| class="wikitable"
! TODO || Code
! TODO || Code
|-
|-
| Parse RFC Time || <source lang="python3">datetime.strptime(s, '%a, %d %b %Y %H:%M:%S GMT')</source>
| Parse RFC Time ||
<source lang="python3">
import time
import datetime
 
# To date object
dt = datetime.datetime.strptime(s, '%a, %d %b %Y %H:%M:%S GMT')
 
# To timestamp
ts = time.mktime(dt.timetuple())
</source>
|}
|}


= Format =
= Formatting =
{| class="wikitable"
{| class="wikitable"
! ||
! TODO || Code
|-
|-
| ||
| To ISO string ||
<source lang="python3">
import os.path
import pytz
import datetime
 
# Without timezone
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(__file__))
print("ISO 8601: %s" % mtime.strftime('%Y-%m-%dT%H:%M:%SZ'))
 
# With timezone
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(__file__), pytz.timezone('Asia/Taipei'))
print("ISO 8601: %s" % mtime.strftime('%Y-%m-%dT%H:%M:%S%z'))
</source>
|-
| To RFC string ||
<source lang="python3">
import os.path
import pytz
import datetime
 
# Without timezone
mtime = datetime.fromtimestamp(os.path.getmtime(__file__))
print("RFC 2822: %s" % mtime.strftime('%a, %d %b %Y %H:%M:%S %Z'))
 
# With timezone
mtime = datetime.fromtimestamp(os.path.getmtime(__file__), pytz.timezone('Asia/Taipei'))
print("RFC 2822: %s" % mtime.strftime('%a, %d %b %Y %H:%M:%S %Z'))
</source>
|}
|}


= Manipulate =
= Manipulate =
{| class="wikitable"
{| class="wikitable"
! ||
! TODO || Code
|-
|-
| ||
| Yesterday ||
<source lang="python">
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d')
</source>
|}
|}

Latest revision as of 08:32, 22 May 2019

Parsing

TODO Code
Parse RFC Time
import time
import datetime

# To date object
dt = datetime.datetime.strptime(s, '%a, %d %b %Y %H:%M:%S GMT')

# To timestamp
ts = time.mktime(dt.timetuple())

Formatting

TODO Code
To ISO string
import os.path
import pytz
import datetime

# Without timezone
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(__file__))
print("ISO 8601: %s" % mtime.strftime('%Y-%m-%dT%H:%M:%SZ'))

# With timezone
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(__file__), pytz.timezone('Asia/Taipei'))
print("ISO 8601: %s" % mtime.strftime('%Y-%m-%dT%H:%M:%S%z'))
To RFC string
import os.path
import pytz
import datetime

# Without timezone
mtime = datetime.fromtimestamp(os.path.getmtime(__file__))
print("RFC 2822: %s" % mtime.strftime('%a, %d %b %Y %H:%M:%S %Z'))

# With timezone
mtime = datetime.fromtimestamp(os.path.getmtime(__file__), pytz.timezone('Asia/Taipei'))
print("RFC 2822: %s" % mtime.strftime('%a, %d %b %Y %H:%M:%S %Z'))

Manipulate

TODO Code
Yesterday
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d')