I'm trying to parse dates in the form of "Sept 9, 2021"
using datetime
I was trying the following format:
"%m %d, %y"
but it raises a ValueError while I'm trying to convert it
(i.e using int(datetime.strptime("Sept 9, 2021","%m %d, %y").timestamp())
)
How can I tell which format am I supposed to use?
Thanks
CodePudding user response:
For strptime
there are different format code than usual.
You use %b
to refer to a Three-digit string month, which means that you must use Sep
instead of Sept
, and you use %Y
to convert a 4 digit year.
So the code would be like the following
int(datetime.datetime.strptime("Sep 9, 2021", "%b %d, %Y").timestamp())
# 1631138400
For more information see Format Codes.
CodePudding user response:
To my knowledge the key work for September is Sep (not Sept).
You can check this link for more details on that: Python Date abbreviation
I advice you to use something similar to this snippet of code:
from datetime import datetime
date_s = "Sep 9, 2021"
datetime_object = datetime.strptime(date_s.upper().replace("SEPT", "SEP"), '%b %d, %Y')
print(datetime_object)
You can also check this Stack thread that seem similar to your question: Date Handling in Python for Sept
CodePudding user response:
ea There are a couple of ways how to get the timestamp from your string:
1. First solution is to use dateparser module from PyPi (pip install dateparser). This module can help you to get datetime object from any string which is similar to datetime string.
Solution:
import dateparser
date_time_object = dateparser.parse("Sept 9, 2021").timestamp()
print(date_time_object)
Result: 1631127600.0
2. The first issue that your string contains one unnecessary string in name of month so this solution is a bit wrong and won't help you but only for understanding I will send
Solution:
from datetime import datetime
time_stamp = int(datetime.strptime("Sep 9, 2021","%b %d, %Y").timestamp())
print(time_stamp)
Result: 1631127600