How to encode time strptime format [duplicate] - python

This question already has answers here:
Detecting date format and converting them to MM-DD-YYYY using Python3
(3 answers)
Closed 3 years ago.
I have a python code for time.strptime and the format is like this:
start_date = time.strptime('2019-03-25', '%Y-%m-%d')
But now if my users try to input the time that is not according to the format it will give an error.
Let's say if users try to input the date format like this:
start_date = time.strptime('25-03-2019', '%Y-%m-%d')
That will give an error message
ValueError: time data '25-03-2019' does not match format '%Y-%m-%d'
So, how to encode the string to automatically give to the format the server provide..?

While there will always be cases that are ambiguous, you can use dateutil (python-dateutil on pypi) to parse dates from most standard formats:
>>> import dateutil
>>> dateutil.parser.parse('25-03-2019')
datetime.datetime(2019, 3, 25, 0, 0)
# ^ ^ ^
# year, month, day

Related

Convert a number sequence into a date using python? (example: 221201) [duplicate]

This question already has answers here:
How can I convert a string into a date object and get year, month and day separately?
(4 answers)
Closed 2 months ago.
I have a bunch of number sequences like "221201" meaning the year 2022, month 12 and day 01 (so 2022-12-01). How can I convert number sequences in this format into the actual date using python?
I've tried using the dateutil library but couldn't figure out how to get it to recognize this format.
from datetime import datetime
date_str = '221201'
date_obj = datetime.strptime(date_str, '%y%m%d')
print(type(date_obj))
print(date_obj) # printed in default format
You can learn more about strptime in this link

Python how to convert datetime.date to the YYYY-MM-DD? [duplicate]

This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 8 months ago.
I have a two million timestamp data. I am trying to find first and last date that to in the YYYY-MM-DD format so I can use them in saving file name. But, I found out that np.unique(df.index) is fast (10s) and produces dates in the
datetime.date(2022, 6, 7) format but df.index.strftime('%Y-%m-%d').unique() gives the output I want but it takes more than 5 min, which is bad. So, I decided to use the former approach.
So, How do I convert something like datetime.date(2022, 6, 7) to'2022-06-07'?
Just put that into the str(...) function:
import datetime
my_date = datetime.date(2022, 6, 7)
print(str(my_date)) # prints 2022-06-07
Technically, you can just print it and not make it a string first. But putting it in str means that instead of printing it, you could save that string to a variable.
If you need more advanced formatting options, then you can do what #FObersteiner suggested. But the format you want happens to be the default, so this will do if you just want that one format
Try this:
# import datetime module
from datetime import datetime
# consider date in string format
my_date = "30-May-2020-15:59:02"
# convert datetime string into date,month,day and
# hours:minutes:and seconds format using strptime
d = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")
# convert datetime format into %Y-%m-%d-%H:%M:%S
# format using strftime
print(d.strftime("%Y-%m-%d-%H:%M:%S"))

How to convert a string with timezone to unix timestamp python? [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 2 years ago.
I have a datetime string I get from a database and I want to convert it to unix timestamp.
I am not sure what is the way to do it.
db_timestamp = '2020-08-05 12:48:50+02:00'
f = '%Y-%m-%d %H:%M:%S%z'
timestamp = datetime.strptime(db_timestamp , f)
TypeError: strptime() argument 1 must be str, not datetime.datetime
Another way I tried was as following
python_timestamp = datetime.isoformat(db_timestamp)
test_timestamp = datetime.strptime(python_timestamp , f)
Then I get the following error
ValueError: time data '2020-08-05T12:48:50+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'
How to fix this error?
What should be the correct string format for db_timestamp?
assuming you run Python 3.7 or higher, what you want is fromisoformat to parse the string and timestamp() to get seconds since the epoch UNIX time (POSIX).
from datetime import datetime
db_timestamp = '2020-08-05 12:48:50+02:00'
# to datetime object:
dt = datetime.fromisoformat(db_timestamp)
# to UNIX time:
ts = dt.timestamp()
print(repr(dt), ts)
>>> datetime.datetime(2020, 8, 5, 12, 48, 50, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))) 1596624530.0

How to convert a string to datetime object [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 5 years ago.
With the time value being:
value = '2017-08-31T02:24:29.000Z'
I try to convert it to a datetime object with:
import datetime
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d %I:%M%p')
But the command crashes with the exception:
ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d %I:%M%p'
You should be using a builtin Python's datautil module instead of date time:
import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)
First of all, you are missing the formatter for the microsecond.
Second of all, there is no second colon for dividing the minute and second.
Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.
Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.
This is your code:
datetime_object = datetime.datetime.strptime(value, '%Y-%m-%dT%I:%M:%S.%fZ')
You should get 2017-08-31 02:24:29 as the value of datetime_object.

How to convert API timestamp into python datetime object [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 8 years ago.
I am getting the following string from an API call:
s = '2014-12-11T20:46:12Z'
How would I then convert this into a python object? Is there an easy way, or should I be splitting up the string, for example:
year = s.split('-')[0]
month = s.split('-')[1]
day = s.split('-')[2]
time = s.split('T')[1]
...etc...
You can use the datetime.datetime.strptime function:
>>> from datetime import datetime
>>> s = '2014-12-11T20:46:12Z'
>>> datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 12, 11, 20, 46, 12)
>>>
For a complete list of the available format codes, see strftime() and strptime() Behavior.
Using datetime should do it, recently I found arrow is also a good library to deal with dates.
import arrow
s = '2014-12-11T20:46:12Z'
your_date = arrow.get(s)
print(t.year) # 2014
print(t.hour) # 20

Categories