how do you format date time in python - python

I have a variable that has value like this:
val='14/12/15 0000'
it is in two digit year/month/day hourminute format.
I need to convert this to epoch time.
I tried this
import datetime
datetime.datetime.strptime(val, "%y/%m/%d %HH%MM").strftime('%s')
I get this error:
ValueError: time data '14/12/15 0000' does not match format '%y/%m/%d %HH%MM'
what am I doing wrong here?

Hours (24 hr) are %H, not %HH, and minutes are %M, not %MM.
datetime.datetime.strptime(val, "%y/%m/%d %H%M").strftime('%s')

You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.string_to_string('14/12/15 0000', '%y/%m/%d %H%M', '%s')
Or even convert directly to a timestamp:
import date_converter
timestamp = date_converter.string_to_timestamp('14/12/15 0000', '%y/%m/%d %H%M')

Related

Format error when trying to parse datetime string using strptime

Trying to parse a datetime string to unix:
from calendar import timegm
from datetime import datetime
print(timegm(datetime.strptime(('2021-07-21 00:00:07.223977216+00:00'), '%Y-%m-%d %H:%M:%S.%f')))
Results in
ValueError: time data '2021-07-21 00:00:07.223977216+00:00' does not match format '%Y-%m-%d %H:%M:%S.%f+00:00'
Tried a lot, cant get anywhere so far ...
Your date is in ISO format, so you can use datetime.fromisoformat:
>>> from datetime import datetime
>>> datetime.fromisoformat("2021-07-21 00:00:07+00:00")
datetime.datetime(2021, 7, 21, 0, 0, 7, tzinfo=datetime.timezone.utc)
So if you look at the format of the date time you are providing, it does not have the fractional seconds the formatter is looking for:
# '2021-07-21 00:00:07+00:00' <- this date time
# '%Y-%m-%d %H:%M:%S.%f' <- in this format, is parsing like below
# 'YYYY-MM-DD HH:MM:SS.ff' (note the ff part is missing, then there's a +00:00 part leftover so the format is breaking)
If you don't need the microseconds, remove the '.%f' part from your format string. Otherwise, if you're parsing a series of values where some have the fractional part, you're going to need to give both options:
try:
timestamp = datetime.strptime(your_string_here, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
timestamp = datetime.strptime(your_string_here, '%Y-%m-%d %H:%M:%S')

string convert to date time in python

I have a list of date time strings like this.
16-Aug-2019
I want to convert the string to 2019-08-01 this date format, and I have tried on this code , but it's getting me an error.
formatd_date = datetime.strptime(formatd_date, '%y-%m-%d')
ValueError: time data 'As-of' does not match format '%y-%m-%d'
If any can help, it will be huge thank.
Convert to datetime format and then convert to string format you want to:
>>> from datetime import datetime
>>> a = "16-Aug-2019"
>>> datetime.strptime(a, "%d-%b-%Y").strftime("%Y-%m-%d")
'2019-08-16'
Documentation: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Just fails because %y is 2-digit year. Use %Y for 4-digit year.

how to convert todays datetime into timestamp

I am tryng to convert date-time into string.
I am searching answer of this question
when i do this
time.mktime(time.strptime('2017-05-01 14:07:19', '%Y-%m-%d %H:%M:%S'))
i am able convert datetime into time-stamp but I want to concert today's date into time-stamp like this:
timenow = datetime.datetime.now()
//timenow = 2017-05-01 14:07:19
time.mktime(time.strptime(timenow, '%Y-%m-%d %H:%M:%S'))
then it throws error TypeError: expected string or buffer even i tried like
time.mktime(time.strptime(str(timenow), '%Y-%m-%d %H:%M:%S'))
then it throws ValueError: unconverted data remains: .067000
How could i convert todays datetime into timestamp
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.timestamp())

Create a datetime from a string representation in a CSV file

I have a CSV file with recorded datetimes with a particular format:
%Y-%m-%d %H:%M:%s %Z
Example:
2017-02-11 14:11:42 PST
I am trying to format the datetime to a friendlier value to use later on.
However, I have been unable to create a datetime object with my code so far.
Here is my code:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y/%m/%d %H:%M:%S %Z")
)
This is the error received:
ValueError: time data '2017-02-11 14:11:42 PST' does not match format %Y/%m/%d %H:%M:%S %Z'
Timezones are often rather wonky when trying to convert from a string. It is often best to deal with the timezone string yourself. Here is a bit of code which separates the timezone from the timestamp, and then converts them separately.
Code:
import datetime as dt
import pytz
my_timezones = dict(
PST='US/Pacific',
)
def convert_my_datetime_str(dt_str):
# split into time and timezone
timestamp, tz_str = dt_str.rsplit(' ', 1)
# convert the date string to datetime
time = dt.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
# get a timezone name
tz = pytz.timezone(my_timezones[tz_str])
# return a timezone aware datetime
return tz.localize(time)
Test Code:
print(convert_my_datetime_str('2017-02-11 14:11:42 PST'))
Results;
2017-02-11 14:11:42-08:00
You should be able to just change the format to match your date strings. In the error, your date string has dashes instead of slashes, so make the format string match:
for r in row:
purchase_date.append(
datetime.strptime(row['purchase-date'], "%Y-%m-%d %H:%M:%S %Z")
)

Convert String to Python datetime Object without Zero Padding

I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM

Categories

Resources