Conversion time from string - python

I have a problem with time conversion in Python:
I try to do this:
from datetime import datetime
date_object = datetime.strptime('12:29:31.181', '%H:%M:%S')
And I receive an error: "ValueError: unconverted data remains: .181"
Can you help me?

You need to add %f for microseconds:
In [335]:
from datetime import datetime
date_object = datetime.strptime('12:29:31.181', '%H:%M:%S.%f')
print(date_object)
1900-01-01 12:29:31.181000
Your format string has to consume all the characters in the passed in string, if any are still remaining then the ValueError is raised.

Related

Subtracting datetime in string format with datetime format

I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.
You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675
Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325
The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.

Python how to check different date formats for multiple string values

I have a set of variables(epoch_time,normal_date,date_time,date_time_zone) which can be passed randomly and based on the string format, I am converting it into my required date format (%Y-%m-%d). My variable can be a string with epoch value or string with date timezone or string with datetime or only date. I have tried the following way and it is always going into the first item only in allowed_date_formats. Can someone suggest me a better approach or help me in resolving the issue.
from datetime import datetime
epoch_time='1481883402'
normal_date="2014-09-03"
date_time=str("2014-05-12 00:00:00")
date_time_zone=str("2015-01-20 08:28:16 UTC")
OP_FORMAT="%Y-%m-%d"
ALLOWED_STRING_FORMATS=["%Y-%m-%d %H:%M:%S %Z","%Y-%m-%d %H:%M:%S","%Y-%m-%d"]
def convert_timestamp(date_timestamp=None):
for format in ALLOWED_STRING_FORMATS:
if datetime.strptime(date_timestamp,format):
d=datetime.strptime(date_timestamp,"%Y-%m-%d")
else:
d = datetime.fromtimestamp((float(date_timestamp) / 1000.), tz=None)
return d.strftime(OP_FORMAT)
print(convert_timestamp(normal_date))
Error that i am getting is
ValueError: time data '2014-09-03' does not match format '%Y-%m-%d %H:%M:%S %Z'
You can use try-except for this.
def convert_timestamp(date_timestamp, output_format="%Y-%m-%d"):
ALLOWED_STRING_FORMATS=[
"%Y-%m-%d %H:%M:%S %Z",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d",
]
for format in ALLOWED_STRING_FORMATS:
try:
d = datetime.strptime(date_timestamp,format):
return d.strftime(output_format)
except ValueError:
pass
try:
# unix epoch timestamp
epoch = int(date_timestamp) / 1000
return datetime.fromtimestamp(epoch).strftime(output_format)
except ValueError:
raise ValueError('The timestamp did not match any of the allowed formats')
Do you need to make sure that only specific formats are allowed?
Otherwise you might consider using the automatic parser from dateutil:
from dateutil import parser
normal_date="2014-09-03"
print(parser.parse(normal_date))

Parse datetime from string in python what can 778 mean?

I need to parse string type value which looks like 017-11-18T05:26:01.778+0000
datetime_object = datetime.strptime(date_in_string, "%Y-%m-%d %H-%M-%S-%j-%f")
but it gives mistake like
ValueError: time data '2017-11-18T05:26:01.778+0000' does not match format '%Y-%m-%d '
Where is my mistake?
from dateutil.parser import parse
parse(date_in_string, fuzzy=True)
you have a timezone parameter also in your date, that's the reason of your error

how do you format date time in 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')

Datetime from strings with microseconds

How to include microseconds to datetime, for example:
import datetime
dt = datetime.datetime.strptime('2010-08-30 15:02:55.730', '%Y-%m-%d %H:%M:%S')
>>> ValueError: unconverted data remains: .730
I want to have microseconds too. What should format string look like? What is the placeholder for microseconds?
dt = datetime.datetime.strptime('2010-08-30 15:02:55.730', '%Y-%m-%d %H:%M:%S.%f')
you can look at:
http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Categories

Resources