PYTHON使用datetime更改日期格式[重复]

iyzzxitl  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(186)
    • 此问题在此处已有答案**:

Parse date string and change format(10个答案)
How to convert a date string to different format [duplicate](2个答案)
昨天关门了。
此帖子在15小时前编辑并提交审查。
我想创建一个function,它将datestring variable转换为date format以便进一步处理。问题是我设法隔离了没有条目"date" : []fields,但我无法创建一个if条件来区分日期格式string
我的代码:
输入:json文件

{
    "entries": [
        {
            "attributes": {
                "cn": "Diana Troy",
                "sn": "Troy",
                "givenName": "Diana",
                "sAMAccountName": "wonder-woman",
                "userAccountControl": 514,
                "whenCreated": "2015-09-22 10:21:02+00:00",
                "whenChanged": "2023-01-11 09:33:59+00:00",
                "lastLogonTimestamp": [],
                "pwdLastSet": "2023-01-11 09:33:59.608543+00:00",
                "accountExpires": "9999-12-31 23:59:59.999999+00:00"
            },
            "dn": "CN=Diana Troy,OU=Users,OU=DC-COMICS,DC=universum,DC=local"
        }
    ]
}

代码:

with open(encoded_retrieved_users, 'r', encoding="UTF-8") as file:
    data = json.load(file)
    retrieved_users = data['entries']
retrieved_users.sort(key=lambda d: d["attributes"]["sn"]) # sortuje po sAMAccountName

def is_value(var):
    if type(var) is int:
        val = var
    elif type(var) is str:
        val = var
    else:
        val = None
    return val

def to_short_date_format(string_to_format):
    if is_value(string_to_format) == None:
        short_date = "NO DATE"
    else:
        short_date = string_to_format
    return short_date

for user in retrieved_users:
    attributes = user['attributes']
    userAccountControl = is_value(attributes['userAccountControl'])

    whenCreated = to_short_date_format(attributes['whenCreated'])
    whenChanged = to_short_date_format(attributes['whenChanged'])
    lastLogonTimestamp = to_short_date_format(attributes['lastLogonTimestamp'])
    pwdLastSet = to_short_date_format(attributes['pwdLastSet'])
    accountExpires = to_short_date_format(attributes['accountExpires'])

    print("userAccountControl | " + str(userAccountControl) + " | " + str(type(userAccountControl)))
    print("whenCreated        | " + whenCreated + " | " + str(type(whenCreated)))
    print("whenChanged        | " + whenChanged + " | " + str(type(whenChanged)))
    print("lastLogonTimestamp | " + str(lastLogonTimestamp) + " | " + str(type(lastLogonTimestamp)))
    print("pwdLastSet         | " + str(pwdLastSet) + " | " + str(type(pwdLastSet)))
    print("accountExpires     | " + accountExpires + " | " + str(type(accountExpires)))
    print("----------------------------------")

输出:

wonder-woman
userAccountControl | 514 | <class 'int'>
whenCreated        | 2015-09-22 10:21:02+00:00 | <class 'str'>
whenChanged        | 2023-01-11 09:33:59+00:00 | <class 'str'>
lastLogonTimestamp | NO DATE | <class 'str'>
pwdLastSet         | 2023-01-11 09:33:59.608543+00:00 | <class 'str'>
accountExpires     | 9999-12-31 23:59:59.999999+00:00 | <class 'str'>
----------------------------------

我想得到什么:

def to_short_date_format(string_to_format):
    if is_value(string_to_format) == None:
        short_date = "NO DATE"
    else:
        if string_to_format == <string format %Y-%m-%d %H:%M:%S%z>
            dt = datetime.strptime(string_to_format, '%Y-%m-%d %H:%M:%S%z')
            short_date = dt.strftime('%Y-%m-%d')
        elif string_to_format == <string format %Y-%m-%d %H:%M:%S.%f%z>
            dt = datetime.strptime(string_to_format, '%Y-%m-%d %H:%M:%S.%f%z')
            short_date = dt.strftime('%Y-%m-%d')
    return short_date

output:
    wonder-woman
    userAccountControl | 514
    whenCreated        | 2015-09-22
    whenChanged        | 2023-01-11
    lastLogonTimestamp | NO DATE
    pwdLastSet         | 2023-01-11
    accountExpires     | 9999-12-31
    ----------------------------------
jdzmm42g

jdzmm42g1#

我可以通过重用你的代码片段来获得输出。小问题是你试图提取的日期格式是错误的:

my_date = "2013-06-10 11:50:16+00:00"
# print(my_date)
# print(type(my_date))

from datetime import datetime
dt =datetime.strptime(my_date, '%Y-%m-%d %H:%M:%S%z')
print(dt)
dt_new = dt.strftime('%Y-%m-%d')

print(dt_new)

输出:

相关问题