How to keep leading zeros in datetime to string conversion? - python

I am facing an issue whenever I try to convert a datetime object into string that has leading zeros in the year
Suppose d is my datetime object:
d = '0021-01-12 03:12:28'
d_str = d.strftime("%Y-%m-%d %H:%M:%S.%f")
The output of printing d_str is always (regardless of %Y or %y)
'21-01-12 03:12:28.000000'
The desired output should have leading zeros for the year
'0021-01-12 03:12:28.000000'
The datetime documentation suggests one of %y or %Y format codes should work, however, I have tried both options and they do not work.
Is there a way to do this using the datetime library or do I need to write custom logic?

Try this (edited to reflect suggestion in comment)
d.strftime("%y-%m-%d %H:%M:%S.%f").zfill(26)

Related

Time value does not match the format. ValueError in python

I am trying to convert a string to datetime object using the strptime function.
I am encountering a ValueError that says format doesn't match, so I did double checking and confirmed that the format in the string matches the format I am passing as the parameter for strptime.
I have also referenced this question: time data does not match format but there the month and year were swapped.
So does this only work with the '%y-%m-%d %H:%M:%S' format or is it dynamic as per the user input like in my case '%y-%m-%d-%H:%M:%S' ?
input:-
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%y-%m-%d-%H:%M:%S')
output
ValueError: time data '2022-09-31-01:17:46' does not match format '%y-%m-%d-%H:%M:%S'
Expected output:
#while printing 'do'
2020-09-31-01:17:46
You're almost there. You need %Y instead of %y since you're providing the year with the century (2022 instead of 22).
Your code would be
from datetime import datetime
stg = "2022-10-31-01:17:46"
do = datetime.strptime(stg, '%Y-%m-%d-%H:%M:%S')

getting value error while using datetime.strptime()

i am using datetime.strptime() in order to convert the timesatmp string received from the API to separate the date and time. one of the example :
from datetime import
datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%f%
and I can't figure out what is wrong with this "2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%f%Z" ?
%Z is Time zone name (empty string if the object is naive). for example UTC. If trailing Z appears in all your strings use Z rather than %Z, that is
import datetime
dt = datetime.datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%fZ")
print(dt)
output
2019-11-14 03:41:12.869000
Just remove the % before Z and it should work!
from datetime import datetime
datetime.strptime("2019-11-14T03:41:12.869000Z","%Y-%m-%dT%H:%M:%S.%fZ")

Python - Converting string to datetime object

I've been trying to convert a timestamp that is a string to a datetime object. The problem is the timestamps formatting. I haven't been able to properly parse the timestamp using datetime.datetime.strptime. I could write my own little parser as its a simple problem but I was hoping to use strptime function, I just need help on the formatting.
Example
import datetime
formater = "%y-%m-%dT%H:%M:%SZ"
str_timestamp = "2021-03-13T18:27:37.60918Z"
timestamp = datetime.datetime.strptime(str_timestamp, formater)
print (timestamp)
Output
builtins.ValueError: time data '2021-03-13T18:27:37.60918Z' does not match format '%y-%m-%dT%H:%M:%SZ'
I'm clearly not symbolizing the formatter properly, the T and Z parts are what I can't account for.
y should be Y. y is for 2 digits year.
You should also take care for the milliseconds with .%f:
%Y-%m-%dT%H:%M:%S.%fZ
This format works:
formater = "%Y-%m-%dT%H:%M:%S.%fZ"
output:
2021-03-13 18:27:37.609180

How to convert Timestamp to specific data time format in python? [duplicate]

This question already has an answer here:
Converting python string to datetime obj with AM/PM
(1 answer)
Closed 2 years ago.
from datetime import datetime
import time
timestamp = 1595059353398/1000
dt_object = datetime.fromtimestamp(timestamp)
date_time = dt_object.strftime("%m/%d/%Y, %H:%M:%S")
print(date_time)
I got the output was 07/18/2020, 13:32:33 but I need
Output Should be : 7/18/2020, 1:32:33 PM in this format
Please see solution and explanatory/advisory notes below.
Solution
from datetime import datetime
import re
format = '%m/%d/%Y %I:%M %p'
timestamp = 1595059353398/1000
dt_object = datetime.fromtimestamp(timestamp)
date_time = dt_object.strftime(format)
date_time = re.sub('(^0)|((?<=\/)0)|(?<=\s)0', '', date_time)
print(date_time)
Format
In format, %I specifies 12-hour clock and %p specifies the locale’s equivalent of either AM or PM - see datetime docs.
re to strip leading zeroes
The solution makes use of the builtin re module to replace any leading zeroes that may be present at the start ((^0)), following any instance of '/' within the string (((?<=\/)0)), or following a space ((?<=\s)0) - as per the desired output described in your question.
I would consider thinking about your requirements some more and evaluating whether or not you actually need to remove leading zeroes - as per the desired output described in original post - working with a fixed length (i.e. allowing leading zeroes) certainly has it's advantages in many use cases.
If you do decide that you no longer want to remove leading zeroes in the string produced you can simply omit the line date_time = re.sub(*args).

Converting string to datetime with milliseconds and timezone - Python

I have the following python snippet:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object
However when I execute the code, I'm getting the following error:
ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'
what's wrong with my matching expression?
EDIT 2: According to this post, strptime doesn't support %z (despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)
Gives the following output:
$ python date.py
2015-01-05 17:47:59
EDIT: Your datetime.strptime argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'
With strptime(), %y refers to
Year without century as a zero-padded decimal number
I.e. 01, 99, etc.
If you want to use the full 4-digit year, you need to use %Y
Similarly, if you want to use the 3-letter month, you need to use %b, not %m
I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
And UTC offset is lowercase z.

Categories

Resources