'How do I convert Date String containing "ET" into Python Date/Time?
I am trying to fetch dates from articles that are given in format like Jan. 23, 2005 11:14 pm ET. What should I pass in strftime to fetch the DateTime from this format? I only need the day, month, and year part only.
Solution 1:[1]
Using strptime():
from datetime import datetime
date = datetime.strptime('Jan. 23, 2005 11:14 pm ET', '%b. %d, %Y %I:%M %p ET')
print(date)
You can then access the year, month and day using date.year, date.month, date.day
Solution 2:[2]
If you just want to fetch day, month, and year from a given string you can use the following code
x = "Jan. 23, 2005 11:14 pm ET"
x = x.split(" ")
date = x[1][:-1]
year = x[2]
month = x[0][:-1]
print("date:", date)
print("month:", month)
print("year:", year)
Solution 3:[3]
Split string on the 3rd whitespace and parse with .strptime. You need to make a datetime first since datetime.date doesn't have a .strptime function:
import datetime
s = "Jan. 23, 2005 11:14 pm ET"
dt = datetime.datetime.strptime(" ".join(s.split(" ")[:3]), "%b. %d, %Y").date()
print(dt)
With non-standard libraries:
import dateutil.parser
import pytz
dt = dateutil.parser.parse(s, tzinfos={"ET": pytz.timezone("US/Eastern")})
print(dt)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Keerthan Chand |
| Solution 3 |
