How to Understand Strptime VS. Strftime

How to understand strptime vs. strftime

The difference between Time and DateTime has to do with implementation. A large amount of the DateTime functionality comes from the Rails world and is an arbitrary date with time of day. It's more of a calendar-based system. Time is measured as seconds since January 1, 1970 UTC and is time-zone agnostic. On some systems it is limited to values between 1901 and 2038, a limitation of how traditionally this value is stored as a signed 32-bit integer, but newer versions of Ruby can handle a much wider range, using a 64-bit value or BigNum as required.

In short, DateTime is what you get from a database in Rails where Time is what Ruby has traditionally used. If you're working with values where dates are important and you want to know things like the end of the month or what day it'll be six weeks ahead, use DateTime. If you're just measuring elapsed time and don't care about that, use Time. They're easy to convert between if necessary.

Date on the other hand is just a calendar date and doesn't have any associated times. You might want to use these where times are irrelevant.

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification. I've rarely seen strptime used since DateTime.parse is usually good at picking up on what's going on, but if you really need to spell it out, by all means use the legacy parser.

What is the difference between strptime and strftime?

strptime translates to

"parse (convert) string to datetime object."

strftime translates to

"create formatted string for given time/date/datetime object according to specified format."

Why do you need strftime?

This is what a datetime object looks like: (2015, 7, 19, 22, 7, 44,
377000)

To someone who isn't quite familiar with this format, with the
exception of the year, what's written up there is not immediately
intuitive. So you probably would be better off with something like
Sun, 19 July, 2015. That's what strftime is used for. You simply need
to learn the proper formatting strings.

One Good Link over SO read about this !

Perl strptime format differs from strftime

The module uses its own implementation of strptime which doesn't understand %F. It doesn't implement its own strftime. It's a disaster waiting to happen - you should definitely use a strftime and strptime that come from the same source. Time::Piece::strptime looks like a desparation move from an era without a widely available, standardized strptime.

Now that strptime is in POSIX, I would expect POSIX.pm to export it so you can use your system's strptime. But apparently that module is also failing to keep up. There is a separate POSIX::strptime module which gives you your C library's strptime without interference. I suggest using that.

Datetime - Strftime and Strptime

A possible solution is to use str.lstrip

Ex:

import datetime
Date = datetime.datetime.today().strftime("%d %B %Y")
print(Date.lstrip("0"))

Output:

9 May 2018

Different order of parameters in strptime and strftime

The general principle is that you put required arguments before optional arguments (and indeed you can't put optional arguments before required arguments only if you were to use keyword arguments, which time.strftime and time.strptime don't support.) Since time.strftime(format) formats the current time, the optional time to use instead of the current time has to be the second argument. And likewise, since time.strptime(string) parses string according to the default format, the format has to be the second argument.

What does the p in strptime stand for?

p = pointer. It returns a pointer to a char.

BTW According to my K&R there is a

char *strpbrk(cs,ct);

This 'p' also refers to the returned pointer.

Converting time format with strftime and strptime

import datetime
a = '1/3/2018'
b = '1:14:12 AM'
in_time = datetime.datetime.strptime(b, "%I:%M:%S %p").time()
print(in_time)
c = datetime.datetime.combine(datetime.datetime.strptime(a, "%d/%m/%Y"), in_time)
print(c.strftime("%d/%m/%Y %I:%M:%S %p"))

Try This:

Repl Link

Difference between datetime.strptime and parse from dateutil?

If you take a look at the repr of your intermediate result (the datetime objects), you notice a difference:

from datetime import datetime
from dateutil.parser import parse

print(repr(datetime.strptime('2015-03-25T19:46:23.286966Z', '%Y-%m-%dT%H:%M:%S.%fZ')))
# datetime.datetime(2015, 3, 25, 19, 46, 23, 286966)

print(repr(parse('2015-03-25T19:46:23.286966Z')))
# datetime.datetime(2015, 3, 25, 19, 46, 23, 286966, tzinfo=tzutc())

The first one is naive, no tzinfo set since you use a literal Z in the parsing directive. The second one is aware; tzinfo is set to UTC since dateutil's parser recognizes the Z to signal UTC. That makes for the difference in the timestamp, since Python treats naive datetime as local time - thus the difference of 1 hour, which is your local time's UTC offset.

You can correctly parse like

print(repr(datetime.fromisoformat('2015-03-25T19:46:23.286966Z'.replace('Z', '+00:00'))))
# datetime.datetime(2015, 3, 25, 19, 46, 23, 286966, tzinfo=datetime.timezone.utc)

see also here.

Or less convenient (imho), with strptime:

print(repr(datetime.strptime('2015-03-25T19:46:23.286966Z', '%Y-%m-%dT%H:%M:%S.%f%z')))
# datetime.datetime(2015, 3, 25, 19, 46, 23, 286966, tzinfo=datetime.timezone.utc)

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.



Related Topics



Leave a reply



Submit