Search code examples
pythondatetimeoutlookpywin32

Get user date format in Windows


My question is similar to this one, however, I don't want to get the date format of the locale, but the one set by the user. The reason is that I am using the pywin32 api to communicate with Outlook, specifically to filter mails by date. The format in which I have to pass the date to the application is the one set by the user, otherwise it won't work.

So the code looks like this:

inbox = outlook.Session.GetSharedDefaultFolder(user, 6)

mails = inbox.Items.Restrict(
            "[ReceivedTime] > '{}'".format(retrieve_from.strftime(local_date_fmt))
)

If anyone knows how to do this without passing the date in the user defined format, that would also solve my problem.

EDIT:

I am referring to the short date format set in the region settings in this window:

Region Settings window

So in this case, local_date_fmt would be set to %Y-%m-%d.


Solution

  • You could use [MS.Learn]: GetDateFormatW function (datetimeapi.h), which is wrapped by [ME.TimGolden]: win32api.GetDateFormat.

    Example:

    >>> import time
    >>> import pywintypes as pwts
    >>> import win32api as wapi
    >>>
    >>> DATE_SHORTDATE = 0x00000001
    >>> DATE_LONGDATE = 0x00000002
    >>>
    >>> cur_time = time.time()
    >>> cur_time
    1567692860.7315922
    >>> time.ctime(cur_time)
    'Thu Sep  5 17:14:20 2019'
    >>>
    >>> wapi.GetDateFormat(0, DATE_SHORTDATE, pwts.Time(cur_time))
    '2019-09-05'
    >>>
    >>> wapi.GetDateFormat(0, DATE_LONGDATE, pwts.Time(cur_time))  # Bonus
    'Thursday, 5 September, 2019'